package com.iris.live.services.services.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.iris.live.services.common.*;
import com.iris.live.services.covervo.DaoFromMap;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.services.BrandService;
import com.iris.live.services.services.InsuranceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Xin on 7/8/2016.
 */
@Service
@Transactional//(readOnly = true)
public class InsuranceServiceImpl implements InsuranceService {
    private static final Logger logger = LoggerFactory.getLogger(InsuranceServiceImpl.class);
    @Autowired
    Lsh库存表Repository lsh库存表Repository;
    @Autowired
    报价付款详细Repository 报价付款详细Repository;
    @Autowired
    报价交车表Repository 报价交车表Repository;
    @Autowired
    Lsh消息Repository lsh消息Repository;
    @Autowired
    Lsh保险申请附属表详细Repository lsh保险申请附属表详细Repository;
    @Autowired
    InsuranceLogRepository insuranceLogRepository;
    @Autowired
    Lsh保险战败原因附属Repository lsh保险战败原因附属Repository;
    @Autowired
    顾客记录汇总Repository 顾客记录汇总Repository;
    @Autowired
    private InsuranceRepository insuranceRepository;
    @Autowired
    private Lsh保险公司设置Repository lsh保险公司设置Repository;
    @Autowired
    private Lsh保险公司使用Repository lsh保险公司使用Repository;
    @Autowired
    private Lsh保险战败原因Repository lsh保险战败原因Repository;
    @Autowired
    private 报价保险表Repository 报价保险表Repository;
    @Autowired
    private 报价保险详细表Repository 报价保险详细表Repository;
    @Autowired
    private Lsh保险手续费Repository lsh保险手续费Repository;
    @Autowired
    private 报价单表Repository 报价单表Repository;
    @Autowired
    private Lsh保险设置Repository lsh保险设置Repository;
    @Autowired
    private Lsh保险申请表Repository lsh保险申请表Repository;
    @Autowired
    private 保险申请附属Repository 保险申请附属repository;
    @Autowired
    private 保险申请表附属详细Repository 保险申请表附属详细repository;
    @Autowired
    private Itask基础设置Repository itask基础设置Repository;
    @Autowired
    private Lsh车型Repository lsh车型Repository;
    @Autowired
    private InsuranceCancelReasonRepository insuranceCancelReasonRepository;
    @Autowired
    private InsuranceEndorsementLogRepository insuranceEndorsementLogRepository;
    @Autowired
    private 报价客户表Repository 报价客户表Repository;
    @Autowired
    private TEndorsementInfoRepository endorsementInfoRepository;
    @Autowired
    private TInsBuyinfoRepository insBuyinfoRepository;
    @Autowired
    private TInsBuyRepository insBuyRepository;
    @Autowired
    private TInsuranceCarInfoRepository insuranceCarInfoRepository;
    @Autowired
    private Lsh保险公司设置Repository 保险公司设置Repository;
    @Autowired
    private IExcelReportService excelReportService;
    @Resource
    private DataRecycleRepository dataRecycleRepository;

    @Resource(name = "ExportOtherInsuranceAccountInfoSource")
    private IExcelReportSource ExportOtherInsuranceAccountInfoSource;

    @Resource(name = "ExportInsuranceAccountInfoSource")
    private IExcelReportSource ExportInsuranceAccountInfoSource;

    @Autowired
    private GroupAreaRepository groupAreaRepository;

    @Autowired
    private BrandService brandService;

    @Override
    public PageData getInsuranceInfoList(String liveName, String permit, GetInsuranceInfoListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetInsuranceInfoListRequest());
        return this.insuranceRepository.getInsuranceInfoList(liveName,permit, request,request.getPageSize(),request.getPageIndex());
    }

    @Override
    public ResultData getInsuranceAccountInfo(String liveName, String permit, GetInsuranceInfoListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetInsuranceInfoListRequest());

        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(this.insuranceRepository.getInsuranceAccountInfo(liveName, request.getPageSize(), request.getPageIndex(), permit,
                    request.tciNo, request.vciNo, request.tciCompany, request.vciCompany, request.salesName, request.status,
                    request.username, request.userPhone, request.vin, request.type, request.startEnterDate,
                    request.endEnterDate, request.startDueDate, request.endDueDate, request.startOrderDate, request.endOrderDate,
                    request.startExpectInvoiceDate, request.endExpectInvoiceDate, request.orderRelyType,
                    request.forceInsuranceStartDate,request.forceInsuranceEndDate,request.commercialInsuranceStartDate,request.commercialInsuranceEndDate));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("台账导出失败");
            logger.error("台账导出失败", e);
        }

        return resultData;
    }

    @Override
    public Object getInsuranceInfoByCode(String permit, int code) {
        return this.insuranceRepository.getInsuranceInfoByCode(permit, code);
    }

    @Override
    public List getInsuranceCompanyList(String permit) {
        GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permit);
        List<String> brands = brandService.getBrandListByArea(groupAreaModel);
        List<Map> list = this.insuranceRepository.getInsuranceCompanyList(permit);

        if (!ApprovalUtils.GROUP_PERMIT.equals(permit)) { //如果为LSH许可,则全部展示
            if (groupAreaModel.getIsDealer() != 1) { // 为区域许可,则过滤适用区域
                list = list.stream()
                        .filter(e -> brands.contains(e.get("brand").toString()) && (e.get("区域许可") == null || e.get("区域许可").toString().equals(permit)))
                        .collect(Collectors.toList());
            } else { // 经销商许可,直接过滤品牌(保险没有适用单店)
                list = list.stream()
                        .filter(e -> brands.contains(e.get("brand").toString()))
                        .collect(Collectors.toList());
            }
        }
        return list;
    }

    @Override
    public List getInsuranceCompanyListByLicense(String license) {
        Assert.hasLength(license);
        return this.insuranceRepository.getInsuranceFeeByLicense(license);
    }

    @Override
    @Transactional
    public Map<String, Object> saveInsuranceCompany(SaveInsuranceCompany model) {
        Assert.notNull(model);
        Map map = new HashMap();
        Lsh保险公司设置Model model1 = new Lsh保险公司设置Model();
        model1.set保险公司(model.保险公司);
        model1.set保险公司编号(model.保险公司编号);
        if (!"全部".equals(model.brand)) {
            model1.setBrand(model.brand);
        }
        if (model.areaId != 0) {
            model1.setAreaId(model.areaId);
        }
        model1.set创建时间(model.创建时间);
        model1.set启用状态(model.启用状态);
        model1.set更新时间(model.更新时间);
        model1.set状态(model.状态);
        model1.set更新账号(model.更新账号);
        Lsh保险公司设置Model model0 = this.lsh保险公司设置Repository.save(model1);

//        Lsh保险公司使用Model modelSY = new Lsh保险公司使用Model();
//        modelSY.set保险公司编号(model0.get保险公司编号());
//        modelSY.set许可(model.许可);
//        modelSY.set使用状态(model.使用状态);
//        modelSY.set更新账号(model.更新账号);
//        modelSY.set更新时间(model.更新时间);
//        map.put("Lsh保险公司使用Model", this.lsh保险公司使用Repository.save(modelSY));
//
//        Lsh保险手续费Model model2 = new Lsh保险手续费Model();
////        model2.set交强险手续费(model.交强险手续费);
//        model2.set保险公司编号(model0.get保险公司编号());
////        model2.set商业险手续费(model.商业险手续费);
//        model2.set备注(model.备注);
//        model2.set许可(model.许可);

        // 将LSH经销商表中存在数据放进 LSH保险公司使用 及 LSH保险手续费
        List dlr = this.insuranceRepository.getDlr();
        for (int i = 0; i < dlr.size(); i++) {
//            Lsh保险公司设置Model lsh保险公司设置Model = new Lsh保险公司设置Model();
            Lsh保险手续费Model lsh保险手续费Model = new Lsh保险手续费Model();
            Lsh保险公司使用Model lsh保险公司使用Model = new Lsh保险公司使用Model();
            String dlrCode = ((Map) dlr.get(i)).get("许可_BMBS").toString();

//            lsh保险公司设置Model.set保险公司编号(model.保险公司编号);
//            lsh保险公司设置Model.set保险公司(model.保险公司);
//            lsh保险公司设置Model.set状态(model.状态);
//            lsh保险公司设置Model.set启用状态(model.启用状态);
//            lsh保险公司设置Model.set创建时间(model.创建时间);
//            lsh保险公司设置Model.set更新账号(model.更新账号);
//            lsh保险公司设置Model.set更新时间(model.更新时间);
//            Lsh保险公司设置Model ids = this.lsh保险公司设置Repository.save(lsh保险公司设置Model);

            lsh保险公司使用Model.set保险公司编号(model0.get保险公司编号());
            lsh保险公司使用Model.set许可(dlrCode);
            lsh保险公司使用Model.set使用状态(model.使用状态);
            lsh保险公司使用Model.set更新账号(model.更新账号);
            lsh保险公司使用Model.set更新时间(model.更新时间);
            map.put("lsh保险公司使用Model", this.lsh保险公司使用Repository.save(lsh保险公司使用Model));

            lsh保险手续费Model.set保险公司编号(model0.get保险公司编号());
            lsh保险手续费Model.set许可(dlrCode);
            lsh保险手续费Model.set交强险手续费(model.交强险手续费);
            lsh保险手续费Model.set商业险手续费(model.商业险手续费);
            lsh保险手续费Model.set备注(model.备注);
            lsh保险手续费Model.set更新时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
//            lsh保险手续费Model.set客户类别(model.客户类别);
//            this.lsh保险手续费Repository.save(lsh保险手续费Model);
            if ("".equals(model.客户类别)) {
                lsh保险手续费Model.set客户类别("1");
                map.put("Lsh保险手续费Model1", this.lsh保险手续费Repository.save(lsh保险手续费Model));

                lsh保险手续费Model.set客户类别("2");
                map.put("Lsh保险手续费Model2", this.lsh保险手续费Repository.save(lsh保险手续费Model));
            } else {
                lsh保险手续费Model.set客户类别(model.客户类别);
                map.put("Lsh保险手续费Model", this.lsh保险手续费Repository.save(lsh保险手续费Model));
            }
            map.put("Lsh保险公司设置Model", model0);
        }
        return map;
    }

    @Override
    public ResultData getInsuranceCompanyByBrand(String brand, String permit,int carID) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            //BUG 8112 常用车型推荐方案设置 和 跟进档案 的 交强险保险公司 修改成调同一接口，这里做整合处理。
            // 常用车型推荐方案设置---调接口   brand  品牌   carID  为  0
            // 跟进档案---调接口            brand  “null”字符串  carID  为   车型编号
            PageData pageData = new PageData();
            Lsh车型Model mode = new Lsh车型Model();
            List list = new ArrayList();
            if (carID != 0){
                mode = lsh车型Repository.findby车型编号(carID);
            }
            if (mode != null && !Strings.isNullOrEmpty(mode.get品牌())){
                list = lsh保险公司设置Repository.getInsuranceCompanyByBrand(mode.get品牌(), permit);
            }else if (!Strings.isNullOrEmpty(brand)  && !"null".equals(brand)){
                list = lsh保险公司设置Repository.getInsuranceCompanyByBrand(brand, permit);
            }
            pageData.setTotal(list.size());
            pageData.setData(list);
            resultData.setPageData(pageData);
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("保险公司查询失败");
            logger.error("保险公司查询失败", e);
        }
        return resultData;
    }

    @Override
    @Transactional
    public List<Map> saveInsuranceCompanyBatch(List<SaveInsuranceCompany> modelList) {
        Assert.notNull(modelList);
        List<Map> list = new ArrayList();
        //循环遍历传入的modelList进行取值
        if (modelList.size() > 0) {
            for (int i = 0; i < modelList.size(); i++) {
                Map<String, Object> map;
                map = (saveInsuranceCompany(modelList.get(i)));
                list.add(map);
            }
        }
        return list;
    }

    @Override
    @Transactional
    public boolean saveInsuranceCompanyStatus(int id, String status) {
        Assert.hasLength(status);
        Lsh保险公司设置Model model = this.lsh保险公司设置Repository.findOne(id);
        model.set启用状态(status);
        this.lsh保险公司设置Repository.save(model);
        return true;
    }

    @Override
    @Transactional
    public boolean saveInsuranceCompanyStatusByLicense(int id, String license, String status) {
//        Lsh保险公司使用ModelPK key = new Lsh保险公司使用ModelPK();
//        key.set保险公司编号(id);
//        key.set许可(license);
        try {
            Lsh保险公司使用Model model = null;//this.lsh保险公司使用Repository.findOne(key);
            List<Lsh保险公司使用Model> list = lsh保险公司使用Repository.select(id, license);
            if (list != null && list.size() > 0) {
                model = list.get(0);
            }
            if (model == null) {
                model = new Lsh保险公司使用Model();
                model.set保险公司编号(id);
                model.set许可(license);
            }
            model.set使用状态(status);
            model.set更新时间(new Timestamp(new Date().getTime()));
            this.lsh保险公司使用Repository.save(model);
            return true;
        } catch (Exception e) {
            logger.info("lsh保险公司使用保存异常:", e.getMessage());
            return false;
        }
    }

    @Override
    public PageData getSuggestPlan(String permit, RequestBase request) {
        request = MoreObjects.firstNonNull(request, new RequestBase());
        PageData list = this.insuranceRepository.getSuggestPlan(permit, request.getPageSize(), request.getPageIndex());
        for (Object data : list.getData()) {
            Map map = (Map) data;
            int carId = Integer.parseInt(map.get("车型编号").toString());
//            String insuranceCompanyId = (String) map.get("保险公司编号");
            map.put("险种", this.insuranceRepository.getDetailsByPlan(permit, carId));
        }
        return list;
    }

    //
    @Override
    @Transactional
    public Lsh保险设置Model saveSuggestPlan(Lsh保险设置Model model) {
        Assert.notNull(model);
        return this.lsh保险设置Repository.save(model);
    }

    @Override
    @Transactional
    public List<Lsh保险设置Model> saveSuggestPlanBatch(String license, int companyId, int companyId1, int carTypeId,
                                                   List<Lsh保险设置Model> modelList, String seatsNumber) {
        Assert.notNull(modelList);
//        this.lsh保险设置Repository.delBy许可And保险公司编号And车型编号(license, companyId, carTypeId);
//        this.lsh保险设置Repository.delBy许可And保险公司编号And车型编号(license, companyId1, carTypeId);
        this.lsh保险设置Repository.delBy许可And车型编号(license, carTypeId);
        this.lsh保险设置Repository.delBy许可And车型编号(license, carTypeId);
        //根据车型编号修改LSH车型表的座位数
        lsh车型Repository.updateSeatsNumberById(carTypeId, seatsNumber);
        return this.lsh保险设置Repository.save(modelList);
    }

    @Override
    public List getFailReason() {
        return this.insuranceRepository.getFailReasonList();
    }

    @Override
    @Transactional
    public boolean saveFailReasonStatus(int id, String status) {
        Assert.hasLength(status);
        return this.lsh保险战败原因Repository.set启用状态By新保战败原因编号(id, status) > 0;
    }

    @Override
    public 报价保险表Model getInsuranceOfferById(int id) {
        return this.报价保险表Repository.findOne(id);
    }

    @Override
    public Map getInsuranceOffersById(int id) {
        Map result = (Map) this.insuranceRepository.getInsuranceOffersById(id);
        报价保险表Model insuranceModel = 报价保险表Repository.findOne(Integer.valueOf(id));
        Integer year = insuranceModel.get一保N年();
        BigDecimal commerFirstYearTotalPrice = insuranceModel.getCommerFirstYearTotalPrice();
        String isCommerTotal = insuranceModel.getIsCommerTotal();
        // 如果是总价模式的话，则设置首年商业险的值为CommerFirstYearTotalPrice这个字段的值
        if (null != insuranceModel && !StringUtils.isNullOrBlank(isCommerTotal) && "1".equals(isCommerTotal)) {
            result.put("首年商业险",commerFirstYearTotalPrice);
            result.put("一保多年商业险保费",null == commerFirstYearTotalPrice ? "0.00" : commerFirstYearTotalPrice.multiply(new BigDecimal(year)));
        }
        return result;
    }

    @Override
    @Transactional
    public ResultData saveInsuranceOffer(报价保险表Model model, String code, String userName, String permit) {
        报价保险表Model newModel = this.报价保险表Repository.findOne(model.get保险编号());
        String insCode = model.get保险编号().toString();
        ResultData resultData = new ResultData();
        try {
            保险申请表附属详细repository.updateModelTimeByCode(model.get交强险开始日期(), model.get交强险结束日期(), model.get商业险开始日期(), model.get商业险结束日期(), code);
            newModel.set交强险保险公司(model.get交强险保险公司());
            newModel.set交强险投保期(model.get交强险投保期());
            if (!"".equals(model.get交强险保单号()) && model.get交强险保单号() != null) {
                newModel.set交强险保单号(model.get交强险保单号());
            }
            newModel.set交强险开始日期(model.get交强险开始日期());
            newModel.set交强险结束日期(model.get交强险结束日期());
            newModel.set商业险保险公司(model.get商业险保险公司());
            newModel.set商业险保单号(model.get商业险保单号());
            if (!"".equals(model.get商业险保单号()) && model.get商业险保单号() != null) {
                newModel.set商业险保单号(model.get商业险保单号());
            }
            //  newModel.set一保N年(model.get一保N年());
            newModel.set商业险开始日期(model.get商业险开始日期());
            newModel.set商业险结束日期(model.get商业险结束日期());
            //  newModel.set车船税(model.get车船税());
            newModel.set交强险预计出单日期(model.get交强险预计出单日期());
            newModel.set交强险出单日期(model.get交强险出单日期());
            newModel.set商业险预计出单日期(model.get商业险预计出单日期());
            newModel.set商业险出单日期(model.get商业险出单日期());
            newModel.set更新时间(new Timestamp(new Date().getTime()));

            Assert.notNull(model);
            InsuranceLogModel insuranceLogModel = new InsuranceLogModel();
            insuranceLogModel.setOrgQsn(code);
            insuranceLogModel.setLogTime(new Timestamp(new Date().getTime()));
            insuranceLogModel.setState("01");
            insuranceLogModel.setLogUser(userName);

            updateInsFactoragea(insCode, code, permit, userName);
       /* Lsh保险申请表Model app = this.lsh保险申请表Repository.findOne(model.get保险编号());
        app.set报价次数(app.get报价次数() == null ? 1 : app.get报价次数() + 1);
        //app.set当前状态("成功出单");
        this.lsh保险申请表Repository.save(app);*/
            this.insuranceLogRepository.save(insuranceLogModel);
            //将报价保险申请附属中的 数据从报价报价客户表中写入
            报价单表Model bjdModel = 报价单表Repository.findBy初始报价编号(code).get(0);
            Lsh保险申请附属Model bao2 = 保险申请附属repository.findOnessss(code);
            bao2.set交强险出单日期(model.get交强险出单日期());
            bao2.set交强险预计出单日期(model.get交强险预计出单日期());
            bao2.set商业险出单日期(model.get商业险出单日期());
            bao2.set商业险预计出单日期(model.get商业险预计出单日期());
            if (bjdModel.get客户详细() != null) {
                报价客户表Model bjkhModel = 报价客户表Repository.findOne(bjdModel.get客户详细());
                bao2.set省份(bjkhModel.get省份());
                bao2.set城市(bjkhModel.get城市());
                bao2.set行政区(bjkhModel.get区域());
                bao2.set邮编(bjkhModel.get邮编());
                bao2.set身份证(bjkhModel.get身份证());
                bao2.set被保人姓名(bjkhModel.get名称());
                bao2.set详细地址(bjkhModel.get详细地址());
                bao2.set联系电话(bjkhModel.get电话());
            }
            保险申请附属repository.save(bao2);
            报价保险表Repository.save(newModel);
            List<报价保险表Model> resulrtList = new ArrayList<>();
            resulrtList.add(newModel);
            resultData.setPageData(new PageData(resulrtList, 0));
            resultData.setMessage("保存成功");
            resultData.setResult("true");
        }catch(AppException e){
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            resultData.setMessage(e.getMessage());
            resultData.setResult("false");
        } catch (Exception e) {
            logger.error("保存报价保险异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public List getInsuranceOfferDetailsByOfferId(int offerId) {
        return this.报价保险详细表Repository.findBy保险编号(offerId);
    }

    @Override
    @Transactional
    public boolean saveInsuranceOfferDetailsVVT(int id, String quCode, List<报价保险详细表Model> modelList, String userName) {
        Assert.notNull(modelList);
        Timestamp ts = new Timestamp(new Date().getTime());
        boolean flag = false;
        try {
            Integer year = modelList.get(0).get第N年();//输入保险第N年


            modelList.get(0).set第N年(1);
            //this.报价保险详细表Repository.delBy保险编号And险种(id, "车船税");
            //   this.lsh保险申请表Repository.set当前状态By保险编号(id, "6");
            //1.修改车船税和 交强险
            this.报价保险详细表Repository.updateJqxSate(id);
            //this.保险申请附属repository.updateInsStateById(quCode, "06", ts, userName);
            报价保险详细表Model newModel = 报价保险详细表Repository.findCarByInsId(id);
            报价保险详细表Model newModel2 = 报价保险详细表Repository.findCarByInsIds(id);
            if (newModel != null) {
                newModel.set原价(modelList.get(0).get原价());
                newModel.set折后价(modelList.get(0).get原价());
                newModel.set更新账号(userName);
                newModel.set更新时间(ts);
            } else {
                newModel = new 报价保险详细表Model();
                newModel.set保险编号(modelList.get(0).get保险编号());
                newModel.set原价(modelList.get(0).get原价());
                newModel.set折后价(modelList.get(0).get原价());
                newModel.set第N年(1);
                newModel.set险种(modelList.get(0).get险种());
                newModel.set更新账号(userName);
                newModel.set更新时间(ts);
            }
            if (newModel2 != null) {
                newModel2.set原价(modelList.get(1).get原价());
                newModel2.set折后价(modelList.get(1).get原价());
                newModel2.set更新账号(userName);
                newModel2.set更新时间(ts);
            } else {
                newModel2 = new 报价保险详细表Model();
                newModel2.set保险编号(modelList.get(1).get保险编号());
                newModel2.set原价(modelList.get(1).get原价());
                newModel2.set折后价(modelList.get(1).get原价());
                newModel2.set第N年(1);
                newModel2.set险种(modelList.get(1).get险种());
                newModel2.set更新账号(userName);
                newModel2.set更新时间(ts);
            }


            newModel = this.报价保险详细表Repository.save(newModel);
            newModel = this.报价保险详细表Repository.save(newModel2);
            //修改保险年份
            报价保险表Model model2 = this.报价保险表Repository.findOne(id);
            model2.set一保N年(year);
            报价保险表Repository.save(model2);

            //存记录
           /* InsuranceLogModel insuranceLogModel = new InsuranceLogModel();
            insuranceLogModel.setOrgQsn(quCode);
            insuranceLogModel.setState("06");
            insuranceLogModel.setLogUser(userName);
            insuranceLogModel.setLogTime(new Timestamp(new Date().getTime()));*/

            List<报价保险详细表Model> resultModelList = this.报价保险详细表Repository.findByInsId(id);
            Integer year1 = 0;
            if (resultModelList != null && resultModelList.size() != 0) {
                year1 = this.报价保险详细表Repository.findByInsId(id).get(0).get第N年();
            } else {
                year1 = newModel.get第N年();
            }

            if (year < year1) {//若输年份小于库中年份  则删除 大于输入的年
                this.报价保险详细表Repository.delBy保险编号AndYear(id, year);
                this.lsh保险申请附属表详细Repository.delBy初始报价单号AndYear(quCode, year.toString());
            } else if (year > year1) {
                do {
                    year1++;
                    报价保险详细表Model model = new 报价保险详细表Model();
                    model.set第N年(year1);
                    model.set险种("自定义险种一");
                    model.set保险编号(id);
                    model.set更新账号(userName);
                    model.set更新时间(ts);
                    this.报价保险详细表Repository.save(model);
                } while (year > year1);
            }
            flag = true;
        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("系统异常。", e);
        }
        return flag;
    }

    @Override
    @Transactional
    public List saveInsuranceOfferDetailsWithoutVVT(int id, List<报价保险详细表Model> modelList) {
        Assert.notNull(modelList);
      /*  this.报价保险详细表Repository.delBy保险编号And险种NotEquals(id, "车船税");*/

        return this.报价保险详细表Repository.save(modelList);
    }

    @Override
    @Transactional
    public boolean deleteInsuranceOfferDetailsWithoutVVT(TradeInsInfo tradeInsInfo) {
        boolean flag = false;
        try {
            String insId = tradeInsInfo.insId;  //保险编号
            Integer id = Integer.parseInt(insId);//转保险编号
            Integer year = Integer.parseInt(tradeInsInfo.year);//输入保险第N年

            Integer year1 = this.报价保险详细表Repository.findByInsId(id).get(0).get第N年();
            if (year < year1) {//若输年份小于库中年份  则删除 大于输入的年
                this.报价保险详细表Repository.delBy保险编号AndYear(id, year);
                this.lsh保险申请附属表详细Repository.delBy初始报价单号AndYear(tradeInsInfo.quCode, tradeInsInfo.year);
            } else if (year > year1) {
                do {
                    year1++;
                    报价保险详细表Model model = new 报价保险详细表Model();
                    model.set第N年(year1);
                    model.set险种("自定义险种一");
                    model.set保险编号(id);
                    this.报价保险详细表Repository.save(model);
                } while (year > year1);
            }
            flag = true;
        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("系统异常。", e);
        }
        return flag;
    }

    @Override
    public Object getFailReasonByInsuranceCode(String code) {
        return this.insuranceRepository.getFailReasonByInsuranceCode(code);
    }

    @Override
    public Object getPreFailReasonByInsuranceCode(String code, String insId) {
        return this.insuranceRepository.getPreFailReasonByInsuranceCode(code, insId);
    }

    @Override
    public List<Lsh保险手续费Model> saveInsuranceCompanyPoundage(List<Lsh保险手续费Model> modelList) {
        Assert.notNull(modelList);
        if (modelList != null && modelList.size() > 0) {
            for (Lsh保险手续费Model mode : modelList) {
                mode.set更新时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
                lsh保险手续费Repository.save(mode);
            }
        }
        return modelList;
    }

    @Override
    @Transactional
    public boolean saveOrderFailReason(String orderId, Integer reasonId, String userName) {
        Boolean flog = false;
        try {
            Timestamp ts = new Timestamp(new Date().getTime());
            int result = this.保险申请附属repository.updateInsStateAndReasonById(reasonId, orderId, "04", ts, userName);
            InsuranceLogModel insuranceLogModel = new InsuranceLogModel();
            insuranceLogModel.setOrgQsn(orderId);
            insuranceLogModel.setState("04");
            insuranceLogModel.setLogUser(userName);
            insuranceLogModel.setLogTime(new Timestamp(new Date().getTime()));
            this.insuranceLogRepository.save(insuranceLogModel);
            if (result < 1) {
                TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            }
            flog = true;
        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("系统异常。", e);
        }
        return flog;

    }

    @Override
    public boolean saveSelectableInsuranceCompanyCount(Itask基础设置Model model) {
        try {
            this.itask基础设置Repository.save(model);
            return true;
        } catch (Exception e) {
            logger.error("系统异常。", e);
            return false;
        }
    }

    @Override
    public Itask基础设置Model getSelectableInsuranceCompanyCount(Itask基础设置Model model) {
        try {
            Itask基础设置ModelPK pk = new Itask基础设置ModelPK();
            pk.set许可(model.get许可());
            pk.set设置项目(model.get设置项目());
            return this.itask基础设置Repository.findOne(pk);
        } catch (Exception e) {
            logger.error("系统异常。", e);

            return null;
        }
    }

    public String getlastUpdateTime() {
        List<Map> list = insuranceRepository.getlastUpdateTime();
        if (list != null && list.size() > 0 && list.get(0).get("更新时间") != null) {
            return list.get(0).get("更新时间").toString();
        }
        return "";
    }


    @Override
    public List getComboList(String permit) {
        GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permit);
        return insuranceRepository.getComboList(permit, groupAreaModel.getBrand());
    }

    @Override
    public List getInsComList() {
        return insuranceRepository.getInsComList();
    }


    @Override
    public List getCoInsCompanyList() {
        List requestList = Lists.newArrayList();
        List areaList = insuranceRepository.getAreaList();//获取大区
        List areasList = insuranceRepository.getAreasList();//获取小区
        List insComListOpen = insuranceRepository.getInsComList();//获取保险公司
        //查询 保险公司对应大区的
        for (Object area : areaList) {
            Map request = Maps.newHashMap();
            request.put("区别", "大区");

            request.put("统计单元", ((Map) area).get("统计单元"));
            request.put("经销商总数", ((Map) area).get("经销商总数"));
            String areaName = ((Map) area).get("大区").toString();
            //拼接保险公司
            for (Object insComOpen : insComListOpen) {
                String rowName = ((Map) insComOpen).get("保险公司").toString();
                Integer id = (Integer) ((Map) insComOpen).get("保险公司编号");
                //查询 保险公司对应大区的的数目
                List coInsCompanyList = insuranceRepository.getCoInsCompanyList(rowName, id, areaName);
                Integer total = new Integer(((Map) coInsCompanyList.get(0)).get(rowName).toString());

                request.put(rowName, total);
            }
            requestList.add(request);
        }

        //查询 保险公司对应小区的
        for (Object area : areasList) {
            Map request = Maps.newHashMap();
            request.put("区别", "小区");
            request.put("统计单元", ((Map) area).get("统计单元"));
            request.put("经销商总数", ((Map) area).get("经销商总数"));
            String areaName = ((Map) area).get("小区").toString();
            //拼接保险公司
            for (Object insComOpen : insComListOpen) {
                String rowName = ((Map) insComOpen).get("保险公司").toString();
                Integer id = (Integer) ((Map) insComOpen).get("保险公司编号");
                //查询 保险公司对应大区的的数目
                List coInsCompanyList = insuranceRepository.getCoInsCompanysList(rowName, id, areaName);
                Integer total = new Integer(((Map) coInsCompanyList.get(0)).get(rowName).toString());

                request.put(rowName, total);
            }
            requestList.add(request);
        }


        return requestList;
    }

    @Override
    public PageData getDealerInsList(RequestBase requestBase) {
        return insuranceRepository.getDealerInsList(requestBase);
    }

    @Override
    public List getInsFailList() {
        return insuranceRepository.getInsFailList();
    }

    @Override
    @Transactional//保险战败标准原因设定-保存/修改
    public boolean updateInsFailList(updateInsFail updateInsFail, String username, String permit) {
        Timestamp now = new Timestamp(new Date().getTime());
        String day = (new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        java.sql.Date nowDay = java.sql.Date.valueOf(day);
        // java.sql.Timestamp nowDay=Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        try {
            if ((!Strings.isNullOrEmpty(updateInsFail.id))) {
                //取出  对应  lsh保险战败原因  表中 新保战败原因编号为id的数据
                Integer id = Integer.parseInt((updateInsFail.id).toString());
                Lsh保险战败原因Model lsh保险战败原因Model = lsh保险战败原因Repository.findByid(id);
                if (!Strings.isNullOrEmpty((updateInsFail.state))) {
                    lsh保险战败原因Model.set启用状态((updateInsFail.state).toString());
                    lsh保险战败原因Model.set更新时间(now);
                }
                if ((!Strings.isNullOrEmpty(updateInsFail.failReason))) {
                    lsh保险战败原因Model.set战败原因(updateInsFail.failReason);
                }
                lsh保险战败原因Repository.save(lsh保险战败原因Model);
                //更改lsh保险战败原因附属  表中对应的
                if ((!Strings.isNullOrEmpty(updateInsFail.reinsFailReason))) {
                    List<Lsh保险战败原因附属Model> lsh保险战败原因附属Models = lsh保险战败原因附属Repository.findByIDclassify(Integer.parseInt((updateInsFail.id)), "保险准战败");

                    Lsh保险战败原因附属Model lsh保险战败原因附属Model = null;
                    if (lsh保险战败原因附属Models != null && lsh保险战败原因附属Models.size() > 0) {
                        lsh保险战败原因附属Model = lsh保险战败原因附属Models.get(0);
                    }

                    //保险准战败  输入为Y  不存在则新增 或存在则不管
                    if ((updateInsFail.reinsFailReason).equals("Y")) {
                        if (lsh保险战败原因附属Model == null) {
                            lsh保险战败原因附属Model = new Lsh保险战败原因附属Model();
                            lsh保险战败原因附属Model.set战败分类("保险准战败");
                            lsh保险战败原因附属Model.set保险战败原因编号(Integer.parseInt((updateInsFail.id)));
                            lsh保险战败原因附属Repository.save(lsh保险战败原因附属Model);
                        }
                    }
                    //保险准战败  输入为N 存在则删除 或不存在不管
                    if ((updateInsFail.reinsFailReason).equals("N")) {
                        if (lsh保险战败原因附属Model != null) {
                            lsh保险战败原因附属Repository.deleteByIDclassify(Integer.parseInt((updateInsFail.id)), "保险准战败");
                        }
                    }
                }

                if (!Strings.isNullOrEmpty(updateInsFail.insFailReason)) {
                    List<Lsh保险战败原因附属Model> lsh保险战败原因附属Models = lsh保险战败原因附属Repository.findByIDclassify(Integer.parseInt((updateInsFail.id)), "保险战败");

                    Lsh保险战败原因附属Model lsh保险战败原因附属Model = null;
                    if (lsh保险战败原因附属Models != null && lsh保险战败原因附属Models.size() > 0) {
                        lsh保险战败原因附属Model = lsh保险战败原因附属Models.get(0);
                    }

                    //保险战败  输入为Y 不存在则新增 或不管
                    if ((updateInsFail.insFailReason).equals("Y")) {
                        if (lsh保险战败原因附属Model == null) {
                            lsh保险战败原因附属Model = new Lsh保险战败原因附属Model();
                            lsh保险战败原因附属Model.set战败分类("保险战败");
                            lsh保险战败原因附属Model.set保险战败原因编号(Integer.parseInt((updateInsFail.id)));
                            lsh保险战败原因附属Repository.save(lsh保险战败原因附属Model);
                        }
                    }
                    //保险战败  输入为 N 存在则删除 或不存在不管
                    if ((updateInsFail.insFailReason).equals("N")) {
                        if (lsh保险战败原因附属Model != null) {
                            lsh保险战败原因附属Repository.deleteByIDclassify(Integer.parseInt((updateInsFail.id)), "保险战败");
                        }
                    }
                }

            } else {
                Lsh保险战败原因Model lsh保险战败原因Model = new Lsh保险战败原因Model();

                //新增 Lsh保险战败原因
                if ((!Strings.isNullOrEmpty(updateInsFail.failReason))) {
                    lsh保险战败原因Model.set战败原因(updateInsFail.failReason);
                }
                if ((!Strings.isNullOrEmpty(updateInsFail.state))) {
                    lsh保险战败原因Model.set启用状态(updateInsFail.state);
                }
                lsh保险战败原因Model.set许可(permit);
                lsh保险战败原因Model.set更新账号(username);
                lsh保险战败原因Model.set更新时间(now);
                lsh保险战败原因Model.set创建日期(nowDay);
                Lsh保险战败原因Model lsh保险战败原因Model1 = lsh保险战败原因Repository.save(lsh保险战败原因Model);
                //若传入保险准战败  则新增 保险准战败
                if ((!Strings.isNullOrEmpty(updateInsFail.reinsFailReason)) && (updateInsFail.reinsFailReason).equals("Y")) {
                    Lsh保险战败原因附属Model lsh保险战败原因附属Model = new Lsh保险战败原因附属Model();
                    lsh保险战败原因附属Model.set战败分类("保险准战败");
                    lsh保险战败原因附属Model.set保险战败原因编号(lsh保险战败原因Model1.get新保战败原因编号());
                    lsh保险战败原因附属Repository.save(lsh保险战败原因附属Model);
                }
                //若传入保险准战败  则新增 保险战败
                if ((!Strings.isNullOrEmpty(updateInsFail.insFailReason)) && (updateInsFail.insFailReason).equals("Y")) {
                    Lsh保险战败原因附属Model lsh保险战败原因附属Model = new Lsh保险战败原因附属Model();
                    lsh保险战败原因附属Model.set战败分类("保险战败");
                    lsh保险战败原因附属Model.set保险战败原因编号(lsh保险战败原因Model1.get新保战败原因编号());
                    lsh保险战败原因附属Repository.save(lsh保险战败原因附属Model);
                }

            }

            return true;
        } catch (Exception e) {
            logger.error("系统异常。", e);

            return false;
        }
    }

    @Override
    public List getRealInsFailList(RealInsFail realInsFail) {
        return insuranceRepository.getRealInsFailList(realInsFail.reason);
    }

    @Override
    /*交强险保单信息—获取*/
    public ResultData getcarForceInsInformation(String InsId) {
        ResultData resultData = new ResultData();
        List date = insuranceRepository.getcarForceInsInformation(InsId);
        if (date != null) {
            resultData.setMessage("查询成功");
            resultData.setResult("true");
            resultData.setPageData(new PageData(date, date.size()));
        } else {
            resultData.setMessage("系统错误，查询失败");
            resultData.setResult("false");
        }

        return resultData;
    }


    @Override
    /*商业险保单信息获取*/
    public ResultData getcarCommercialInsInformation(String InsId) {
        ResultData resultData = new ResultData();
        List date = insuranceRepository.getcarCommercialInsInformation(InsId);
        if (date != null) {
            resultData.setMessage("查询成功");
            resultData.setResult("true");
            resultData.setPageData(new PageData(date, date.size()));
        } else {
            resultData.setMessage("系统错误，查询失败");
            resultData.setResult("false");
        }

        return resultData;
    }

    @Override
    public ResultData getTradeInsInfoList(TradeInsInfo tradeInsInfo) {
        ResultData resultData = new ResultData();
        List data = this.insuranceRepository.getTradeInsInfoList(tradeInsInfo);
        if (data != null) {
            resultData.setMessage("查询成功");
            resultData.setResult("true");
            resultData.setPageData(new PageData(data, data.size()));
        } else {
            resultData.setMessage("系统错误，查询失败");
            resultData.setResult("false");
        }
        return resultData;
    }


    @Transactional
    public ResultData savecarForceInsInformation(String InsId, String saveid, getUpdateInsuranceOrderInfo realInsFail, String poseman) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            String endorsementId = realInsFail.InsuranceOrderRelyId;

            // 批减、批退时，校验批单金额是否大于保费
            if (checkEndorsement(realInsFail, resultData)) return resultData;

            // 校验批单号是否已经存在
            checkEndorsementId(resultData, endorsementId);
            if ("false".equals(resultData.getResult())) return resultData;

//            if (realInsFail.InsuranceOrderRelyId == null) {
//                // 如果 批单号 为空 那么 需要 发送 消息给 销售顾问
//                //推送消息
//                //极光推送消息
//                String content = "";
//                //  JsonObject json = JsonObjectUtils.getJsonObject();
//                List recList = new ArrayList();
//                //  recList.add();
//                //JPush.SendPushITaskForAndroidAndIos(content, content, json, recList);
//            }

            报价保险表Model bao1 = 报价保险表Repository.findOne(Integer.parseInt(InsId));
            Lsh保险申请附属Model bao2 = 保险申请附属repository.findOnessss(saveid);
            if (!"".equals(realInsFail.InsuranceOutCompany) && realInsFail.InsuranceOutCompany != null) {
                bao1.set交强险保险公司(realInsFail.InsuranceOutCompany);
            } else {
                bao1.set交强险保险公司(null);
            }

            if (!"".equals(realInsFail.InsuranceOutDt) && realInsFail.InsuranceOutDt != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date dates = sdf.parse(realInsFail.InsuranceOutDt);
                bao1.set交强险出单日期(dates);
            } else {
                bao1.set交强险出单日期(null);
            }

            if (!"".equals(realInsFail.InsuranceOutCompany) && realInsFail.InsuranceOutCompany != null) {

                bao1.set交强险保险公司(realInsFail.InsuranceOutCompany);
            } else {
                bao1.set交强险保险公司(null);
            }

            if (!"".equals(realInsFail.InsuranceStarUseDt) && realInsFail.InsuranceStarUseDt != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date datess1 = sdf.parse(realInsFail.InsuranceStarUseDt);
                bao1.set交强险开始日期(datess1);
            } else {
                bao1.set交强险开始日期(null);
            }


            if (!"".equals(realInsFail.InsuranceEndUseDt) && realInsFail.InsuranceEndUseDt != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date datess2 = sdf.parse(realInsFail.InsuranceEndUseDt);
                bao1.set交强险结束日期(datess2);
            } else {
                bao1.set交强险结束日期(null);
            }


            if (!"".equals(realInsFail.InsuranceOutSumDt) && realInsFail.InsuranceOutSumDt != null) {

                bao1.set交强险投保期(Integer.parseInt(realInsFail.InsuranceOutSumDt));
            } else {
                bao1.set交强险投保期(null);
            }


            if (!"".equals(realInsFail.InsuranceOrderId) && realInsFail.InsuranceOrderId != null) {

                bao1.set交强险保单号(realInsFail.InsuranceOrderId);
            } else {
                bao1.set交强险保单号(null);
            }


            bao1.set更新账号(poseman);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Timestamp ts = new Timestamp(System.currentTimeMillis());

            bao1.set更新时间(ts);
            报价保险表Repository.save(bao1);
            if (!"".equals(realInsFail.UserName) && realInsFail.UserName != null) {
                bao2.set被保人姓名(realInsFail.UserName);
            } else {
                bao2.set被保人姓名(null);
            }


            if (!"".equals(realInsFail.UserSex) && realInsFail.UserSex != null) {
                if (realInsFail.UserSex.equals("男")) {
                    bao2.set被保人称谓("先生");
                } else {
                    bao2.set被保人称谓("女士");
                }

            } else {
                bao2.set被保人称谓(null);
            }


            if (!"".equals(realInsFail.UserType) && realInsFail.UserType != null) {
                bao2.set客户类型(realInsFail.UserType);
            } else {
                bao2.set客户类型(null);
            }

            if (!"".equals(realInsFail.UserTel) && realInsFail.UserTel != null) {
                bao2.set联系电话(realInsFail.UserTel);
            } else {
                bao2.set联系电话(null);
            }

            if (realInsFail.UserIdCard != null && !"".equals(realInsFail.UserIdCard)) {
                bao2.set身份证(realInsFail.UserIdCard);

            }
            if (realInsFail.UserOrganizeCode != null && !"".equals(realInsFail.UserOrganizeCode)) {
                bao2.set身份证(realInsFail.UserOrganizeCode);
            }

            if (!"".equals(realInsFail.UserAddrCode) && realInsFail.UserAddrCode != null) {
                bao2.set邮编(realInsFail.UserAddrCode);
            } else {
                bao2.set邮编(null);
            }


            if (!"".equals(realInsFail.UserAddrCity1) && realInsFail.UserAddrCity1 != null) {
                bao2.set省份(realInsFail.UserAddrCity1);
            } else {
                bao2.set省份(null);
            }

            if (!"".equals(realInsFail.UserAddrCountry2) && realInsFail.UserAddrCountry2 != null) {
                bao2.set城市(realInsFail.UserAddrCountry2);
            } else {
                bao2.set城市(null);
            }
            if (!"".equals(realInsFail.UserAddrIsland3) && realInsFail.UserAddrIsland3 != null) {
                bao2.set行政区(realInsFail.UserAddrIsland3);
            } else {
                bao2.set行政区(null);
            }
            if (!"".equals(realInsFail.UserAddrDetai4) && realInsFail.UserAddrDetai4 != null) {
                bao2.set详细地址(realInsFail.UserAddrDetai4);
            } else {
                bao2.set详细地址(null);
            }


            bao2.set更新账号(poseman);
            bao2.set更新时间(ts);

            保险申请附属repository.save(bao2);

            int iss = Integer.parseInt(InsId);

            // 批单类型不为空时，保存批单信息   (批退时，批单号可以为空；批增和批减时批单号不可以为空)
            if (!StringUtils.isNullOrBlank(realInsFail.insuranceOrderRelyType)) {
                // 批单信息插入
                Lsh保险申请表附属详细Model newmodel = new Lsh保险申请表附属详细Model();
                newmodel.set许可(realInsFail.permit);
                // 有三个 需要 必须插入
           /*     newmodel.set保险编号(iss);*/
                newmodel.set第N年("1");
                newmodel.set类型("0");
                newmodel.set更新账号(poseman);
                newmodel.set更新时间(ts);
                newmodel.set初始报价单号(saveid);
                if (!"".equals(realInsFail.InsuranceOrderRelyId) && realInsFail.InsuranceOrderRelyId != null) {

                    newmodel.set批单号(realInsFail.InsuranceOrderRelyId);
                } else {
                    newmodel.set批单号(null);
                }
                if (!"".equals(realInsFail.InsuranceOrderRelyDt) && realInsFail.InsuranceOrderRelyDt != null) {

                    Date datess434 = sdf.parse(realInsFail.InsuranceOrderRelyDt);
                    java.sql.Date datesql212 = new java.sql.Date(datess434.getTime());
                    newmodel.set批单日期(datesql212);
                } else {
                    newmodel.set批单日期(null);

                }
                if (!"".equals(realInsFail.InsuranceOrderRelyOutDt) && realInsFail.InsuranceOrderRelyOutDt != null) {

                    Date datess333 = sdf.parse(realInsFail.InsuranceOrderRelyOutDt);

                    String reason = realInsFail.retreatReason;
                    java.sql.Date datesql873 = new java.sql.Date(datess333.getTime());
                    newmodel.set退保日期(datesql873);
                    newmodel.set退保备注(reason);
                } else {
                    newmodel.set退保日期(null);
                }

                if (!"".equals(realInsFail.insuranceOrderRelyType) && realInsFail.insuranceOrderRelyType != null) {
                    newmodel.set批单类型(realInsFail.insuranceOrderRelyType);
                }  //交强险的 需要修改的

                //迁移了数据  1021-1040行  2017/04/01
                if (!"".equals(realInsFail.InsuranceOrderId) && realInsFail.InsuranceOrderId != null) {
                    newmodel.set交强险保单号(realInsFail.InsuranceOrderId);
                } else {
                    newmodel.set交强险保单号(null);
                }

                if (!"".equals(realInsFail.InsuranceStarUseDt) && realInsFail.InsuranceStarUseDt != null) {
                    Date datess1 = sdf.parse(realInsFail.InsuranceStarUseDt);
                    newmodel.set交强险开始日期(datess1);
                } else {
                    newmodel.set交强险开始日期(null);
                }
                if (!"".equals(realInsFail.InsuranceEndUseDt) && realInsFail.InsuranceEndUseDt != null) {

                    Date datess2 = sdf.parse(realInsFail.InsuranceEndUseDt);
                    newmodel.set交强险结束日期(datess2);
                } else {
                    newmodel.set交强险结束日期(null);
                }

                // 设置批单金额
                if (null != realInsFail.endorsementMoney) {
                    newmodel.setEndorsementMoney(new BigDecimal(new DecimalFormat("#.00").format(realInsFail.endorsementMoney)));
                } else {
                    newmodel.setEndorsementMoney(null);
                }

                // 计算手续费
                BigDecimal poundage = setPoundageOfThisShop(realInsFail, 0);
                newmodel.setPoundage(poundage);

                保险申请表附属详细repository.save(newmodel);
            }

            // 没有批单的时候
            else {
                List<Lsh保险申请表附属详细Model> forceInsurances = 保险申请表附属详细repository.getForceInsuranceByCode(saveid);
                if (forceInsurances != null && !forceInsurances.isEmpty()) {
                    保险申请表附属详细repository.updateForceInsurancesNumberByCode(sdf.parse(realInsFail.InsuranceStarUseDt), sdf.parse(realInsFail.InsuranceEndUseDt), realInsFail.InsuranceOrderId, saveid);
                } else {
                    Lsh保险申请表附属详细Model model = new Lsh保险申请表附属详细Model();
                    model.set许可(realInsFail.permit);
                    model.set第N年("1");
                    model.set类型("0");
                    if (!"".equals(realInsFail.InsuranceOrderId) && realInsFail.InsuranceOrderId != null) {
                        model.set交强险保单号(realInsFail.InsuranceOrderId);
                    } else {
                        model.set交强险保单号(null);
                    }

                    if (!"".equals(realInsFail.InsuranceStarUseDt) && realInsFail.InsuranceStarUseDt != null) {
                        Date datess1 = sdf.parse(realInsFail.InsuranceStarUseDt);
                        model.set交强险开始日期(datess1);
                    } else {
                        model.set交强险开始日期(null);
                    }
                    if (!"".equals(realInsFail.InsuranceEndUseDt) && realInsFail.InsuranceEndUseDt != null) {

                        Date datess2 = sdf.parse(realInsFail.InsuranceEndUseDt);
                        model.set交强险结束日期(datess2);
                    } else {
                        model.set交强险结束日期(null);
                    }
                    model.set更新账号(poseman);
                    model.set更新时间(ts);
                    model.set初始报价单号(saveid);
                    保险申请表附属详细repository.save(model);
                }
            }

            // 报价保险表Repository.save(bao1);
            //保险申请附属repository.save(bao2);
            Timestamp tsss = new Timestamp(System.currentTimeMillis());
            报价保险详细表ModelPK itemson = new 报价保险详细表ModelPK();
            itemson.set保险编号(Integer.parseInt(InsId));
            itemson.set第N年(1);
            itemson.set险种("交强险");

            报价保险详细表Model newitem = 报价保险详细表Repository.findOne(itemson);
            if (newitem != null && !"".equals(newitem)) {
                if (!"".equals(realInsFail.InsuranceMoney) && realInsFail.InsuranceMoney != null) {
                    newitem.set原价(realInsFail.InsuranceMoney);
                } else {
                    newitem.set原价(new BigDecimal(0));
                }
                if (!"".equals(realInsFail.InsuranceMoney) && realInsFail.InsuranceMoney != null) {
                    newitem.set折后价(realInsFail.InsuranceMoney);
                } else {
                    newitem.set折后价(new BigDecimal(0));
                }
                newitem.set更新时间(tsss);
                newitem.set更新账号(poseman);
                报价保险详细表Repository.save(newitem);
            } else {
                报价保险详细表Model newitemsontwo = new 报价保险详细表Model();
                newitemsontwo.set保险编号(Integer.parseInt(InsId));
                newitemsontwo.set第N年(1);
                newitemsontwo.set险种("交强险");
                newitemsontwo.set更新时间(tsss);
                newitemsontwo.set更新账号(poseman);
                if (!"".equals(realInsFail.InsuranceMoney) && realInsFail.InsuranceMoney != null) {
                    newitemsontwo.set原价(realInsFail.InsuranceMoney);
                } else {
                    newitemsontwo.set原价(new BigDecimal(0));
                }
                if (!"".equals(realInsFail.InsuranceMoney) && realInsFail.InsuranceMoney != null) {
                    newitemsontwo.set折后价(realInsFail.InsuranceMoney);
                } else {
                    newitemsontwo.set折后价(new BigDecimal(0));
                }

                报价保险详细表Repository.save(newitemsontwo);

            }

            报价保险详细表ModelPK modelPKVehicle = new 报价保险详细表ModelPK();
            modelPKVehicle.set保险编号(Integer.parseInt(InsId));
            modelPKVehicle.set第N年(1);
            modelPKVehicle.set险种("车船税");

            报价保险详细表Model modelVehicle = 报价保险详细表Repository.findOne(modelPKVehicle);
            if (modelVehicle != null && !"".equals(modelVehicle)) {
                if (!"".equals(realInsFail.vehicleAndVesselTax) && realInsFail.vehicleAndVesselTax != null) {
                    modelVehicle.set原价(new BigDecimal(Double.parseDouble(realInsFail.vehicleAndVesselTax)));
                } else {
                    modelVehicle.set原价(new BigDecimal(0));
                }
                if (!"".equals(realInsFail.vehicleAndVesselTax) && realInsFail.InsuranceMoney != null) {
                    modelVehicle.set折后价(new BigDecimal(Double.parseDouble(realInsFail.vehicleAndVesselTax)));
                } else {
                    modelVehicle.set折后价(new BigDecimal(0));
                }
                newitem.set更新时间(new Timestamp(new Date().getTime()));
                newitem.set更新账号(poseman);
                报价保险详细表Repository.save(modelVehicle);
            } else {
                报价保险详细表Model model = new 报价保险详细表Model();
                model.set保险编号(Integer.parseInt(InsId));
                model.set第N年(1);
                model.set险种("车船税");
                model.set更新时间(new Timestamp(new Date().getTime()));
                model.set更新账号(poseman);
                if (!"".equals(realInsFail.vehicleAndVesselTax) && realInsFail.vehicleAndVesselTax != null) {
                    model.set原价(new BigDecimal(Double.parseDouble(realInsFail.vehicleAndVesselTax)));
                } else {
                    model.set原价(new BigDecimal(0));
                }
                if (!"".equals(realInsFail.vehicleAndVesselTax) && realInsFail.vehicleAndVesselTax != null) {
                    model.set折后价(new BigDecimal(Double.parseDouble(realInsFail.vehicleAndVesselTax)));
                } else {
                    model.set折后价(new BigDecimal(0));
                }

                报价保险详细表Repository.save(model);

            }
            resultData.setResult("true");
            resultData.setMessage("保存成功");
        } catch (Exception e) {
            logger.error("保存出错", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            resultData.setResult("false");
            resultData.setMessage("保存失败");
        }

        return resultData;
    }

    // 这是 商业险
    @Transactional
    public ResultData saveCommercialInsInformation(String InsId, String saveid, String year, getUpdateInsuranceOrderInfo realInsFail, String poseman, String tYear) {
        ResultData resultData = new ResultData("false",null,null);
        try {
            // 批减、批退时，校验批单金额是否大于保费
            if (checkEndorsement(realInsFail, resultData)) return resultData;

            String endorsementId = realInsFail.InsuranceOrderRelyId;
            // 校验批单号是否已经存在
            checkEndorsementId(resultData, endorsementId);
            if ("false".equals(resultData.getResult())) return resultData;

//            if (realInsFail.InsuranceOrderRelyId == null) {
//                // 如果 批单号 为空 那么 需要 发送 消息给 销售顾问
//                //推送消息
//                //极光推送消息
//                String content = "";
//                //  JsonObject json = JsonObjectUtils.getJsonObject();
//                List recList = new ArrayList();
//                //  recList.add();
//                //JPush.SendPushITaskForAndroidAndIos(content, content, json, recList);
//            }

            报价保险表Model bao1 = 报价保险表Repository.findOne(Integer.parseInt(InsId));
            Lsh保险申请附属Model bao2 = 保险申请附属repository.findOnessss(saveid);
            if (!"".equals(realInsFail.InsuranceOutCompany) && realInsFail.InsuranceOutCompany != null) {
                bao1.set商业险保险公司(realInsFail.InsuranceOutCompany);
            } else {
                bao1.set商业险保险公司(null);
            }


            if ("".equals(realInsFail.InsuranceOutDt) || realInsFail.InsuranceOutDt == null) {

                bao1.set商业险出单日期(null);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date dates = sdf.parse(realInsFail.InsuranceOutDt);
                bao1.set商业险出单日期(dates);
            }


            if (!"".equals(realInsFail.InsuranceStarUseDt) && realInsFail.InsuranceStarUseDt != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date datess1 = sdf.parse(realInsFail.InsuranceStarUseDt);
                bao1.set商业险开始日期(datess1);
            } else {
                bao1.set商业险开始日期(null);
            }


            if (!"".equals(realInsFail.InsuranceEndUseDt) && realInsFail.InsuranceEndUseDt != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date datess2 = sdf.parse(realInsFail.InsuranceEndUseDt);
                bao1.set商业险结束日期(datess2);
            } else {
                bao1.set商业险结束日期(null);
            }


            if (!"".equals(realInsFail.InsuranceOutSumDt) && realInsFail.InsuranceOutSumDt != null) {

                bao1.set商业险投保期(Integer.parseInt(realInsFail.InsuranceOutSumDt));
            } else {
                bao1.set商业险投保期(null);
            }


            if (!"".equals(realInsFail.InsuranceOrderId) && realInsFail.InsuranceOrderId != null) {

                bao1.set商业险保单号(realInsFail.InsuranceOrderId);
            } else {
                bao1.set商业险保单号(null);
            }


            bao1.set更新账号(poseman);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Timestamp ts = new Timestamp(System.currentTimeMillis());

            bao1.set更新时间(ts);
            报价保险表Repository.save(bao1);

            if (!"".equals(realInsFail.UserName) && realInsFail.UserName != null) {
                bao2.set被保人姓名(realInsFail.UserName);
            } else {
                bao2.set被保人姓名(null);
            }


            if (!"".equals(realInsFail.UserSex) && realInsFail.UserSex != null) {
                if (realInsFail.UserSex.equals("男")) {
                    bao2.set被保人称谓("先生");
                } else {
                    bao2.set被保人称谓("女士");
                }

            } else {
                bao2.set被保人称谓(null);
            }


            if (!"".equals(realInsFail.UserType) && realInsFail.UserType != null) {
                bao2.set客户类型(realInsFail.UserType);
            } else {
                bao2.set客户类型(null);
            }

            if (!"".equals(realInsFail.UserTel) && realInsFail.UserTel != null) {
                bao2.set联系电话(realInsFail.UserTel);
            } else {
                bao2.set联系电话(null);
            }

            if (realInsFail.UserIdCard != null && !"".equals(realInsFail.UserIdCard)) {
                bao2.set身份证(realInsFail.UserIdCard);
            }

            if (realInsFail.UserOrganizeCode != null && !"".equals(realInsFail.UserOrganizeCode)) {
                bao2.set身份证(realInsFail.UserOrganizeCode);
            }

            if (!"".equals(realInsFail.UserAddrCode) && realInsFail.UserAddrCode != null) {
                bao2.set邮编(realInsFail.UserAddrCode);
            } else {
                bao2.set邮编(null);
            }


            if (!"".equals(realInsFail.UserAddrCity1) && realInsFail.UserAddrCity1 != null) {
                bao2.set省份(realInsFail.UserAddrCity1);
            } else {
                bao2.set省份(null);
            }

            if (!"".equals(realInsFail.UserAddrCountry2) && realInsFail.UserAddrCountry2 != null) {
                bao2.set城市(realInsFail.UserAddrCountry2);
            } else {
                bao2.set城市(null);
            }
            if (!"".equals(realInsFail.UserAddrIsland3) && realInsFail.UserAddrIsland3 != null) {
                bao2.set行政区(realInsFail.UserAddrIsland3);
            } else {
                bao2.set行政区(null);
            }
            if (!"".equals(realInsFail.UserAddrDetai4) && realInsFail.UserAddrDetai4 != null) {
                bao2.set详细地址(realInsFail.UserAddrDetai4);
            } else {
                bao2.set详细地址(null);
            }
            bao2.set更新账号(poseman);
            bao2.set更新时间(ts);

            保险申请附属repository.save(bao2);

            int iss = Integer.parseInt(InsId);

            // 批单类型不为空，保存批单信息
            if (!StringUtils.isNullOrBlank(realInsFail.insuranceOrderRelyType)) {
                // 批单信息插入
                Lsh保险申请表附属详细Model newmodel = new Lsh保险申请表附属详细Model();
                newmodel.set许可(realInsFail.permit);
                // 有三个 需要 必须插入
           /*     newmodel.set保险编号(iss);*/
                //判断是否为退保  是退保则删除该年里的保险信息，且在保险申请附属详情里增加该退保数据。
                if (tYear != "0") {
                    报价保险详细表Repository.delBy保险编号AndYearT(Integer.parseInt(InsId), Integer.parseInt(tYear));
                }
                if (!"".equals(realInsFail.InsuranceOrderRelyOutDt)) {
                    newmodel.set第N年(tYear);
                } else {
                    newmodel.set第N年(year);
                }
                //迁移了数据  1265-1286行  2017/04/01
                if (!"".equals(realInsFail.InsuranceOrderId) && realInsFail.InsuranceOrderId != null) {

                    newmodel.set商业险保单号(realInsFail.InsuranceOrderId);
                } else {
                    newmodel.set商业险保单号(null);
                }
                if (!"".equals(realInsFail.InsuranceStarUseDt) && realInsFail.InsuranceStarUseDt != null) {

                    Date datess1 = sdf.parse(realInsFail.InsuranceStarUseDt);
                    newmodel.set商业险开始日期(datess1);
                } else {
                    newmodel.set商业险开始日期(null);
                }

                if (!"".equals(realInsFail.InsuranceEndUseDt) && realInsFail.InsuranceEndUseDt != null) {
                    Date datess2 = sdf.parse(realInsFail.InsuranceEndUseDt);
                    newmodel.set商业险结束日期(datess2);
                } else {
                    newmodel.set商业险结束日期(null);
                }

                newmodel.set类型("1");
                newmodel.set更新账号(poseman);
                newmodel.set更新时间(ts);
                newmodel.set初始报价单号(saveid);
                if (!"".equals(realInsFail.InsuranceOrderRelyId) && realInsFail.InsuranceOrderRelyId != null) {

                    newmodel.set批单号(realInsFail.InsuranceOrderRelyId);
                } else {
                    newmodel.set批单号(null);
                }
                if (!"".equals(realInsFail.InsuranceOrderRelyDt) && realInsFail.InsuranceOrderRelyDt != null) {

                    Date datess434 = sdf.parse(realInsFail.InsuranceOrderRelyDt);
                    java.sql.Date datesqlnini = new java.sql.Date(datess434.getTime());
                    newmodel.set批单日期(datesqlnini);
                } else {
                    newmodel.set批单日期(null);

                }
                if (!"".equals(realInsFail.InsuranceOrderRelyOutDt) && realInsFail.InsuranceOrderRelyOutDt != null) {
                    Date datess33 = sdf.parse(realInsFail.InsuranceOrderRelyOutDt);
                    String reason = realInsFail.retreatReason;
                    java.sql.Date datesqlternini5 = new java.sql.Date(datess33.getTime());
                    newmodel.set退保日期(datesqlternini5);
                    newmodel.set退保备注(reason);
                } else {
                    newmodel.set退保日期(null);
                }
                java.sql.Date endzhi = null;
                if (!"".equals(realInsFail.InsuranceOrderRelyDt) && realInsFail.InsuranceOrderRelyDt != null) {
                    endzhi = resultReTrue(realInsFail.InsuranceOrderRelyDt, realInsFail.MaxYear);
                    //
                    newmodel.set保单终止日期(endzhi);
                }
                if (!"".equals(realInsFail.insuranceOrderRelyType) && realInsFail.insuranceOrderRelyType != null) {
                    newmodel.set保单终止日期(endzhi);
                }

                if (!"".equals(realInsFail.insuranceOrderRelyType) && realInsFail.insuranceOrderRelyType != null) {
                    newmodel.set批单类型(realInsFail.insuranceOrderRelyType);
                }
                // 设置批单金额
                if (null != realInsFail.endorsementMoney) {
                    newmodel.setEndorsementMoney(new BigDecimal(new DecimalFormat("#.00").format(realInsFail.endorsementMoney)));
                } else {
                    newmodel.setEndorsementMoney(null);
                }
                // 计算手续费
                BigDecimal poundage = setPoundageOfThisShop(realInsFail, 1);
                newmodel.setPoundage(poundage);
                保险申请表附属详细repository.save(newmodel);


                // 这是 查出  第一年的 数据  商业险  第一年  确定的 一个初始报价编号 的  List
                List<Lsh保险申请表附属详细Model> isResult = 保险申请表附属详细repository.getModelBypidanhaoAndYearBussinessInsurance(saveid);
                // 报价单号 + 商业险 所有的
                List<Lsh保险申请表附属详细Model> isResults = 保险申请表附属详细repository.getModelThreeBussinessInsurance(saveid);

                //查出所有的 最新的 更新时间 对应的  id
                List idlist = insuranceRepository.findQuanClassAndidMaxDate(saveid);

                Timestamp ts2 = new Timestamp(System.currentTimeMillis());
                // 先把 第一年的 终止日期拿出来
                Map idmaps = new HashMap();
                String idStrs = null;
                int idints = 0;
                java.util.Date firstyear = null;
                Lsh保险申请表附属详细Model fuzhis = null;
                if (idlist != null && idlist.size() > 0) {
                    for (int j = 0; j < idlist.size(); j++) {
                        idmaps = (Map) idlist.get(j);
                        idStrs = idmaps.get("id").toString();
                        idints = Integer.parseInt(idStrs);
                        fuzhis = 保险申请表附属详细repository.findIdandFirstYear(idints);
                        if (fuzhis != null) {
                            firstyear = fuzhis.get批单日期();
                        }
                    }
                }
                // 如果 第一年 的 批单日期 不存在  那么 同样也是 置空
                if (firstyear != null && !"".equals(firstyear)) {
                    String strfirstyear = sdf.format(firstyear);
                    java.sql.Date endfirstyearsum = resultReTrue(strfirstyear, realInsFail.MaxYear);

                    Map idmap = new HashMap();
                    String idStr = null;
                    int idint = 0;
                    Lsh保险申请表附属详细Model fuzhi = null;

                    if (isResult != null && isResult.size() > 0) {
                        //如果 第一年 存在，那么 将第一年的 计算出来的  终止日期 赋值给 其他 N年的
                        for (int i = 0; i < idlist.size(); i++) {
                            idmap = (Map) idlist.get(i);
                            idStr = idmap.get("id").toString();
                            idint = Integer.parseInt(idStr);
                            fuzhi = 保险申请表附属详细repository.findOne(idint);
                            fuzhi.set保单终止日期(endfirstyearsum);

                            保险申请表附属详细repository.save(fuzhi);
                        }
                    } else {
                        // 如果 第一年不存在 ，那么 直接把所有的  N年 全部的 终止日期清空
                        if (isResults != null && isResults.size() > 0) {
                            for (int i = 0; i < isResults.size(); i++) {
                                Lsh保险申请表附属详细Model qingkong = isResults.get(i);
                                qingkong.set保单终止日期(null);

                                保险申请表附属详细repository.save(qingkong);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < isResults.size(); i++) {
                        Lsh保险申请表附属详细Model qingkong = isResults.get(i);
                        qingkong.set保单终止日期(null);
                        保险申请表附属详细repository.save(qingkong);
                    }
                }
            }

            resultData.setResult("true");
            resultData.setMessage("保存成功");
        } catch (Exception e) {
            logger.error("保存出错", e);
            resultData.setResult("false");
            resultData.setMessage("保存失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }


    private java.sql.Date resultReTrue(String stardate, String zi) {
        java.sql.Date d = null;
        Integer sum = Integer.parseInt(zi);
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date todayDate = formatter.parse(stardate);

            long afterTime = (todayDate.getTime() / 1000) + 60 * 60 * 24 * 365 * sum;
            todayDate.setTime(afterTime * 1000);
            String afterDate = formatter.format(todayDate);
            // 获得了 一年后的  多了一天
            // 现在需要 获得 的 前一天的
            Calendar c = Calendar.getInstance();
            java.util.Date date = null;
            date = formatter.parse(afterDate);

            c.setTime(date);
            int day = c.get(Calendar.DATE);
            c.set(Calendar.DATE, day - 1);

            String dayBefore = formatter.format(c.getTime());
            d = java.sql.Date.valueOf(LocalDate.parse(dayBefore));

        } catch (Exception e) {
            logger.error("时间转化出了问题", e);
        }
        return d;
    }


    //先删除，在 插入  根据 传入的 第N年 + 保险编号
    @Transactional
    public boolean saveInsuranceFeeAndDelete(int trueId, int trueyear, List<getTypeInsurance> realInsFail, String zhanghao) {
        try {
            报价保险详细表Repository.delBybianhaoAndNian(trueId, trueyear);

            // 然后再 循环的 插入
            for (int i = 0; i < realInsFail.size(); i++) {
                getTypeInsurance allin = realInsFail.get(i);

                报价保险详细表Model newallin = new 报价保险详细表Model();
                newallin.set保险编号(trueId);
                newallin.set第N年(trueyear);
                newallin.set险种(allin.type);

                if (!"".equals(allin.baoe) && allin.baoe != null) {
                    newallin.set参数(allin.baoe);
                } else {
                    newallin.set参数(null);
                }

                if (!"".equals(allin.mainpei) && allin.mainpei != null) {
                    newallin.set不计免赔(allin.mainpei);
                } else {
                    newallin.set不计免赔(null);
                }

                if (!"".equals(allin.baofei) && allin.baofei != null) {
                    newallin.set原价(new BigDecimal(allin.baofei));
                } else {
                    newallin.set原价(new BigDecimal(0));
                }
                if (!"".equals(allin.baofei) && allin.baofei != null) {
                    newallin.set折后价(new BigDecimal(allin.baofei));
                } else {
                    newallin.set折后价(new BigDecimal(0));
                }

                newallin.set更新账号(zhanghao);
                Timestamp ts = new Timestamp(System.currentTimeMillis());
                newallin.set更新时间(ts);
                报价保险详细表Repository.save(newallin);
            }
        } catch (Exception e) {
            logger.error("系统异常。", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean sendInsInfo(SendInsInfo sendInsInfo, String permit, String userName) {
        boolean flag = false;
        try {
            String call;
            String salesCode  = sendInsInfo.salesCode;
            String phone = sendInsInfo.teleNumber;
            String sex =  顾客记录汇总Repository.findCusByCustomerIDAndPhone(salesCode,phone);
            if("男".equals(sex)){
                call="先生";
            }else if ("女".equals(sex)){
                call="女士";
            }else {
                call="先生/女士";
            }
            if ("新保未报价".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，需要进行新保报价，请跟进";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("保险", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "保险", news,
                        userName, sendInsInfo.teleNumber);
            } else if ("新保报价完成".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，新保报价已完成，请查看。";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("保险", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "保险", news,
                        userName, sendInsInfo.teleNumber);
            } else if ("新保出单完成".equals(sendInsInfo.state)) {
                String news = "客户:" + sendInsInfo.cusName + call+"，电话号码:" + sendInsInfo.teleNumber + "，新保出单完成，请查看。";
                //极光推送
                JsonObject json = JsonObjectUtils.getJsonObject("保险", null, null, sendInsInfo.teleNumber, null, sendInsInfo.salesCode);
                List sendName = Lists.newArrayList();
                sendName.add(sendInsInfo.salesCode);
                JPush.SendPushITaskForAndroidAndIos(news, news, json, sendName);
                //存入lsh数据库
                LshMsgUtils.getLshMsg(permit, userName, permit, sendInsInfo.salesCode, "保险", news,
                        userName, sendInsInfo.teleNumber);
            }
            flag = true;
        } catch (Exception e) {
            logger.error("保险消息发送异常", e);
            System.out.print(e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

    @Override
    public ResultData getInsIcWorkInfo(String permit, String userName) {
        ResultData resultData = new ResultData();
        List data = this.insuranceRepository.getInsIcWorkInfo(permit, userName);
        if (data != null) {
            resultData.setMessage("查询成功");
            resultData.setResult("true");
            resultData.setPageData(new PageData(data, data.size()));
        } else {
            resultData.setMessage("系统错误，查询失败");
            resultData.setResult("false");
        }
        return resultData;
    }

    @Override
    public ResultData getInsCarInfo(String code) {
        ResultData resultData = new ResultData();
        List data = this.insuranceRepository.getInsCarInfo(code);
        if (data != null) {
            resultData.setMessage("查询成功");
            resultData.setResult("true");
            resultData.setPageData(new PageData(data, data.size()));
        } else {
            resultData.setMessage("系统错误，查询失败");
            resultData.setResult("false");
        }
        return resultData;
    }

    @Override
    public ResultData updateInsSate(String code, String sate, String userName) {
        ResultData resultData = new ResultData();
        try {
            Timestamp ts = new Timestamp(new Date().getTime());
            //修改保险状态
            this.保险申请附属repository.updateInsStateById(code, sate, ts, userName);
            //修改保险日志
            InsuranceLogModel insuranceLogModel = new InsuranceLogModel();
            insuranceLogModel.setOrgQsn(code);
            insuranceLogModel.setLogTime(new Timestamp(new Date().getTime()));
            insuranceLogModel.setState(sate);
            insuranceLogModel.setLogUser(userName);
            this.insuranceLogRepository.save(insuranceLogModel);

            resultData.setMessage("修改成功");
            resultData.setResult("true");
        } catch (Exception e) {
            logger.error("修改保险状态失败", e);
            resultData.setMessage("系统错误，修改失败");
            resultData.setResult("false");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public ResultData getInsHistoryInfo(String code) {
        ResultData resultData = new ResultData();
        try {
            List<Lsh保险申请表附属详细Model> resulrtList = this.lsh保险申请附属表详细Repository.getInfoBycode(code);
            resultData.setPageData(new PageData(resulrtList, 0));
            resultData.setMessage("获取成功");
            resultData.setResult("true");
        } catch (Exception e) {
            logger.error("保险申请附属历史记录获取失败", e);
            resultData.setMessage("系统错误，获取失败");
            resultData.setResult("false");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }
    private Boolean updateInsFactoragea(String inscode, String code, String permit, String userName) throws Exception {
        boolean flog = false;
        double jqFactorage = 0;
        double syFactorage = 0;
        Lsh保险申请附属Model lsh保险申请附属Model = 保险申请附属repository.findOnessss(code);
        报价保险表Model 报价保险表model = 报价保险表Repository.findOne(Integer.parseInt(inscode));
        String state = lsh保险申请附属Model.get客户类型();
        if (state != null && state.equals("公司")) {
            state = "2";
        } else {
            state = "1";
        }

        GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permit);
        String brand = groupAreaModel.getBrand();

        //获取保险信息  及 保险公司编号
        List<报价单表Model> quotationList = 报价单表Repository.getQuotationListByInitNo(code);
        for(报价单表Model model : quotationList){
            if(StringUtils.isNotNullOrBlank(model.get保险编号()) && model.get保险编号().toString().equals(inscode)){
                Lsh车型Model 车型Model = this.lsh车型Repository.getOne(model.get车型编号());
                brand = 车型Model.get品牌();
            }
        }

        List result = insuranceRepository.getInsPrice(groupAreaModel.getParentId(),permit, inscode,brand);
        if (result != null) {
            Map map = (Map) result.get(0);
            if(logger.isDebugEnabled()){
                logger.debug("inscode={}, info ={}", inscode, JsonObjectUtils.writeAsJson(map));
            }
            Object a = map.get("交强险");
            Object b = map.get("商业险");
            Double jqPrice = 0.0;
            Double syPrice = 0.0;
            if (a != null) {
                jqPrice = Double.parseDouble(map.get("交强险").toString());
            }
            if (b != null) {
                syPrice = Double.parseDouble(map.get("商业险").toString());
            }

            if (map.get("交强险公司编号") != null && map.get("商业险公司编号") != null) {
                String jqID = map.get("交强险公司编号").toString();
                String syID = map.get("商业险公司编号").toString();
                List result2 = insuranceRepository.getInsFactorage(jqID, syID, permit, state);
                if (result2 != null) {
                    Map map1 = (Map) result2.get(0);

                    if (StringUtils.isNullOrBlank(map1.get("交强险手续费"))) {
                        throw new AppException("保存失败，请检查所选保险公司交强险手续费比例设置是否存在！！");
                    }

                    if (StringUtils.isNullOrBlank(map1.get("商业险手续费"))) {
                        throw new AppException("保存失败，请检查所选保险公司商业险手续费比例设置是否存在！！");
                    }

                    Double jq = Double.parseDouble(map1.get("交强险手续费").toString());
                    Double sy = Double.parseDouble(map1.get("商业险手续费").toString());
                    jqFactorage = jq * jqPrice / 100;
                    syFactorage = sy * syPrice / 100;
                }
            } else {
                if (StringUtils.isNullOrBlank(map.get("交强险公司编号"))) {
                    throw new AppException("保存失败，请检查所选保险公司交强险手续费比例设置是否存在！！");
                }

                if (StringUtils.isNullOrBlank(map.get("商业险公司编号"))) {
                    throw new AppException("保存失败，请检查所选保险公司商业险手续费比例设置是否存在！！");
                }
            }
        }

        BigDecimal f1 = new BigDecimal(jqFactorage);
        BigDecimal f2 = new BigDecimal(syFactorage);
        double jFactorage = f1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        //注意事项：此处setCharge方法 计算了所有对应险种的手续费、返回值是：商业险手续费
        BigDecimal Change = setCharge(result, permit, state, inscode);
        BigDecimal sFactorage = Change.setScale(2, BigDecimal.ROUND_HALF_UP);
        // Integer jFactorage = (int) jqFactorage;
        //  Integer sFactorage = (int) syFactorage;
        报价保险表model.set交强险手续费("" + jFactorage + "");
        报价保险表model.set商业险手续费("" + sFactorage + "");
        报价保险表Repository.save(报价保险表model);
        flog = true;
        return flog;
    }


    @Transactional
    @Override
    public ResultData updateInsFactorage(String inscode, String code, String permit, String userName) {
        ResultData resultData = new ResultData();
        try {
            updateInsFactoragea(inscode, code, permit, userName);

            // 更新首年商业险总价 (跟手机端itask选择商业险为总价模式的时候，数据进行同步)
            updateCommerFirstYearTotalPrice(inscode);

            resultData.setMessage("手续费计算成功");
            resultData.setResult("true");
        } catch (AppException e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            resultData.setMessage(e.getMessage());
            resultData.setResult("false");
        } catch (Exception e) {
            logger.error("保险手续费更新", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            resultData.setMessage("保存失败，请检查所选保险公司手续费比例设置是否不存在！！");
            resultData.setResult("false");
        }

        return resultData;
    }


    @Override
    public ResultData updateInsuranceByQuote(String quote, String userName) {
        ResultData rd = new ResultData();
        try {
            Lsh保险申请附属Model model = 保险申请附属repository.findOnessss(quote);
            if (model == null) {
                rd.setResult("false");
                rd.setMessage("未找到该初始报价单号的信息");
                return rd;
            } else {
                if (model.get操作人() == null || "".equals(model.get操作人()) || userName.equals(model.get操作人())) {
                    Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
                    保险申请附属repository.updateInsById(model.getId(), ts, userName);
                    rd.setResult("true");
                    rd.setMessage("修改成功!");
                    return rd;
                } else {
                    rd.setResult("false");
                    rd.setMessage("当前操作人不是登录人");
                    return rd;
                }
            }
        } catch (Exception e) {
            logger.error("更新保险申请附属表失败！", e);
            rd.setMessage("系统错误，获取失败");
            rd.setResult("false");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return rd;
        }
    }

    @Override
    public ResultData getconfirmInsState(String userName, String qucode, String logTime) {
        ResultData rd = new ResultData();
        try {
            //逻辑错误 当前时间永远是最新时间
           /* Date now = new Date();
            SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logTime = myFmt2.format(logTime);*/
            List resultList = insuranceRepository.getconfirmInsState(userName, qucode, logTime);
            if (resultList.size() == 0) {
                rd.setResult("true");
                rd.setMessage("无人操作");
                return rd;
            } else {
                rd.setResult("false");
                rd.setMessage("已有其他专员操作，请刷新保险列表后,重新进行操作！");
                return rd;
            }
        } catch (Exception e) {
            logger.error("查询当前操作人失败！", e);
            rd.setMessage("系统错误，获取失败");
            rd.setResult("false");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return rd;
        }
    }

    @Override
    public ResultData saveInsCarInfo(InsCarInfo insCarInfo) {
        ResultData rd = new ResultData();
        try {
            //保存机动车种类等信息
            Lsh库存表Model lsh库存表Model = lsh库存表Repository.findOne(insCarInfo.invId);
            lsh库存表Model.set机动车种类(insCarInfo.insCarType);
            lsh库存表Model.set核载人数(insCarInfo.manCount);
            lsh库存表Model.set核载质量(insCarInfo.quality);
            lsh库存表Model.set排量(insCarInfo.displacement);
            lsh库存表Model.set功率(insCarInfo.power);
            lsh库存表Repository.save(lsh库存表Model);
            //保存牌照信息
            报价交车表Model 报价交车表model = 报价交车表Repository.findby编号(insCarInfo.submitCarID);
            报价交车表model.set牌照号(insCarInfo.carID);
            报价交车表Repository.save(报价交车表model);
            //保存使用性质和登记日期
            Lsh保险申请附属Model lsh保险申请附属Model = 保险申请附属repository.findOnessss(insCarInfo.quCode);
            lsh保险申请附属Model.set使用性质(insCarInfo.useType);
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String date = insCarInfo.registerDate;
            //Date dateD=sdf1.parse(date);
            lsh保险申请附属Model.set登记日期(java.sql.Date.valueOf(date));
            rd.setResult("true");
            rd.setMessage("保存成功");
            return rd;
        } catch (Exception e) {
            logger.error("保存保险车辆信息错误！", e);
            logger.info(JsonObjectUtils.writeAsJson(insCarInfo));
            rd.setMessage("系统错误，保存失败");
            rd.setResult("false");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return rd;
        }
    }

    @Override
    public ResultData getInsCost(String insCode) {
        ResultData rd = new ResultData();
        try {
            List<Map> resultList = insuranceRepository.getInsCost(insCode);
            报价保险表Model insuranceModel = 报价保险表Repository.findOne(Integer.valueOf(insCode));
            Integer year = insuranceModel.get一保N年();
            BigDecimal commerFirstYearTotalPrice = insuranceModel.getCommerFirstYearTotalPrice();
            String isCommerTotal = insuranceModel.getIsCommerTotal();
            // 如果是总价模式的话，则设置首年商业险的值为CommerFirstYearTotalPrice这个字段的值
            if (null != insuranceModel && !StringUtils.isNullOrBlank(isCommerTotal) && "1".equals(isCommerTotal)) {
                resultList.get(0).put("首年商业险",commerFirstYearTotalPrice);
                resultList.get(0).put("一保多年商业险保费",null == commerFirstYearTotalPrice ? "0.00" : commerFirstYearTotalPrice.multiply(new BigDecimal(year)));
            }
            rd.setPageData(new PageData(resultList, 0));
            rd.setMessage("获取成功");
            rd.setResult("true");
            return rd;
        } catch (Exception e) {
            logger.error("获取保险费用！", e);
            rd.setMessage("系统错误，获取失败");
            rd.setResult("false");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            return rd;
        }
    }

    @Override
    public ResultData getPolicyReasonInfo(String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = Lists.newArrayList();
            list = insuranceRepository.getPolicyReasonInfo(permit);
            resultData.setResult("true");
            resultData.setMessage("成功");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("撤单信息获取失败", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public ResultData saveRevokeInfo(String permit, String userName, InsurancePolicyReason reason) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (reason.id != null && !"".equals(reason.id)) {
                InsuranceCancelReasonModel model = insuranceCancelReasonRepository.findOne(reason.id);

                if (reason.reason != null && !"".equals(reason.reason)) {
                    model.setCancelReason(reason.reason);
                }
                if (reason.state != null && !"".equals(reason.state)) {
                    model.setState(reason.state);
                }
                model.setPermit(permit);
                model.setUpdateTime(new Timestamp(new Date().getTime()));
                model.setUpdateUser(userName);
                insuranceCancelReasonRepository.save(model);
                resultData.setMessage("修改成功");
                resultData.setResult("true");
            } else {
                InsuranceCancelReasonModel model = new InsuranceCancelReasonModel();
                List list = insuranceCancelReasonRepository.findInsuranceCancelReasonModel(reason.reason);

                if (list != null && list.size() > 0) {
                    resultData.setMessage("保存失败，该原因已经存在");
                } else {
                    if (reason.reason != null && !"".equals(reason.reason)) {
                        model.setCancelReason(reason.reason);
                    }
                    if (reason.state != null && !"".equals(reason.state)) {
                        model.setState(reason.state);
                    }
                    model.setPermit(permit);
                    model.setCreateTime(new Timestamp(new Date().getTime()));
                    model.setUpdateTime(new Timestamp(new Date().getTime()));
                    model.setUpdateUser(userName);
                    insuranceCancelReasonRepository.save(model);
                    resultData.setMessage("保存成功");
                    resultData.setResult("true");
                }

            }
        } catch (Exception e) {
            resultData.setMessage("系统错误保存失败");
            logger.error("撤单原因保存失败", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public ResultData saveInsuranceEndorsementLog(String userName, List<InsuranceService.InsuranceEndorsementLog> insuranceEndorsementLog) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间

            for (InsuranceEndorsementLog log : insuranceEndorsementLog) {
                InsuranceEndorsementLogModel logModel = new InsuranceEndorsementLogModel();
                logModel.setEndorsementCode(log.endorsementCode);//批单号
                logModel.setOrgQuoteId(log.orgQuoteId);//初始报价单号
                logModel.setInsuranceName(log.insuranceName);//险种
                logModel.setYearNum(log.yearNum);//第几年
                logModel.setParameter(log.parameter);//参数
                logModel.setIop(log.iop);//不计免赔
                logModel.setSubParameter(log.subParameter);//附加参数
                logModel.setFinPrice(log.finPrice);//原价
                logModel.setOrgPrice(log.orgPrice);//折后价
                logModel.setUpdateUser(userName);//更新人
                logModel.setUpdateTime(nowdate);//更新时间
                insuranceEndorsementLogRepository.save(logModel);
            }
            resultData.setResult("true");
            resultData.setMessage(" 保存成功");

        } catch (Exception e) {
            resultData.setMessage("保存失败");
            logger.error("保险日志保存失败", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public ResultData getOtherInsuranceInfo(String permit, OtherInsuranceInfo otherInsuranceInfo) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(insuranceRepository.getOtherInsuranceInfo(permit, otherInsuranceInfo));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            System.out.print(e);
            resultData.setMessage("获取失败");
            logger.error("他店保险", e);
        }
        return resultData;
    }

    @Override
    public ResultData getOthergetInsuranceAccountInfo(String permit, OtherInsuranceInfo otherInsuranceInfo) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(insuranceRepository.exportOtherInsuranceAccountInfo(permit, otherInsuranceInfo.icPolicyNo, otherInsuranceInfo.bcPolicyNo, otherInsuranceInfo.icInsuranceCpy, otherInsuranceInfo.bcInsuranceCpy,
                    otherInsuranceInfo.sale, otherInsuranceInfo.cusName, otherInsuranceInfo.carBrand, otherInsuranceInfo.carModel, otherInsuranceInfo.getPageSize(), otherInsuranceInfo.getPageIndex()));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            System.out.print(e);
            resultData.setMessage("获取失败");
            logger.error("他店保险台账", e);
        }
        return resultData;
    }

    @Override
    public void exportOtherInsuranceAccountInfo(String permit, OtherInsuranceInfo otherInsuranceInfo, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/LSH_经销商_他店保险业务台账模板.xlsx")
                    .setFileName("经销商_他店保险业务台账模板.xlsx")
                    .setSource(ExportOtherInsuranceAccountInfoSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(65)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("icPolicyNo", otherInsuranceInfo.icPolicyNo)
                    .addParam("bcPolicyNo", otherInsuranceInfo.bcPolicyNo)
                    .addParam("icInsuranceCpy", otherInsuranceInfo.icInsuranceCpy)
                    .addParam("bcInsuranceCpy", otherInsuranceInfo.bcInsuranceCpy)
                    .addParam("sale", otherInsuranceInfo.sale)
                    .addParam("cusName", otherInsuranceInfo.cusName)
                    .addParam("carBrand", otherInsuranceInfo.carBrand)
                    .addParam("carModel", otherInsuranceInfo.carModel)
                    .addParam("pageSize", otherInsuranceInfo.getPageSize())
                    .addParam("pageIndex", otherInsuranceInfo.getPageIndex());

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出他店保险台账异常", e);
        }
    }

    @Override
    public ResultData getInsuranceOtherCarInfo(String vin) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(new PageData(insuranceRepository.getInsuranceOtherCarInfo(vin), 0));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("他店保险车辆", e);
        }

        return resultData;
    }

    @Override
    public ResultData getInsuranceOtherICInfo(String vin) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(new PageData(insuranceRepository.getInsuranceOtherICInfo(vin), 0));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("他店保险交强险", e);
        }

        return resultData;
    }

    @Override
    public ResultData getInsuranceBcInfo(String vin) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(new PageData(insuranceRepository.getInsuranceBcInfo(vin), 0));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("他店保险商业险", e);
        }

        return resultData;
    }

    /*
    carid  必传
    carNumber(车牌号)
    vehicleType(机动车种类
    bBenz(是否奔驰)
    carBrand(品牌)
    carLevel(级别)
    carModel(车型)
    carDetail(车款)
    useCharacter(使用性质)
    motorNumber(发动机号码)
    registerDate(登记日期)
    vin(VIN码)
    passengerNumber(核定载客人数)
    passengerQuality(核定载客质量)
    displacement(排量)
    capacity(功率)*/
    @Override
    public ResultData saveInsuranceOtherCarInfo(SaveInsuranceOtherCarInfo info, String userName, String permit) {
        ResultData resultData = new ResultData("false", null, null);

        try {
            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间

            TInsuranceCarInfoModel carInfoModel = null;
            if (info.carid != null) {
                carInfoModel = insuranceCarInfoRepository.findOne(info.carid);
            } else {
                carInfoModel = new TInsuranceCarInfoModel();
                carInfoModel.setPermit(permit);
                carInfoModel.setSales(userName);
            }
            carInfoModel.setBenz(info.bBenz);
            carInfoModel.setCarnumber(info.carNumber);
            carInfoModel.setCartype(info.vehicleType);
            carInfoModel.setBrand(info.carBrand);
            carInfoModel.setRank(info.carLevel);
            carInfoModel.setModel(info.carModel);
            carInfoModel.setModelshort(info.carDetail);
            carInfoModel.setUsetype(info.useCharacter);
            carInfoModel.setEnginenumber(info.motorNumber);
            carInfoModel.setCheckdate(info.registerDate);
            carInfoModel.setVin(info.vin);
            carInfoModel.setPeopleNo(info.passengerNumber);
            carInfoModel.setWeight(info.passengerQuality);
            carInfoModel.setDisplacement(info.displacement);
            carInfoModel.setPower(info.capacity);
            carInfoModel.setUpdateid(userName);
            carInfoModel.setUpdatetime(nowdate);
            carInfoModel = insuranceCarInfoRepository.save(carInfoModel);

            //保存一个购买信息
            TInsBuyModel insBuyModel = insBuyRepository.findByCarId(carInfoModel.getCarid());
            if (insBuyModel == null) {
                insBuyModel = new TInsBuyModel();
                insBuyModel.setCarid(carInfoModel.getCarid());
            }
            insBuyModel.setUpdateid(userName);
            insBuyModel.setUpdatetime(nowdate);
            insBuyRepository.save(insBuyModel);//保存并返回

            List a = new ArrayList();
            Map b = new HashMap();
            b.put("carid", carInfoModel.getCarid());
            a.add(b);
            resultData.setPageData(new PageData(a, 0));
            resultData.setResult("true");
            resultData.setMessage(" 保存成功");

        } catch (Exception e) {
            resultData.setMessage("保存失败");
            logger.error("他店保险车辆保存失败", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    /*   carid  必传
    1  cusName(姓名)//
    1     sexuallity(性别)
    1     cusType(客户类型)
    1     id(身份编号)
    1     cusTel(客户电话)
    1    province(省份)
    1    city(城市)
    1     region(行政区)
    1    postNumber(邮编)
    1    detailAddress(详细地址)
    1   issuingDate(出单日期)
    1    preiod(投保期)
    1   insuranceCpy(保险公司)
    1     additionalPremium(保费)
    1      policyNumber(保单号)
    1      invalidStart(有效期开始)
    1 invalidEnd(有效期结束)
       policyTerminationDate(保单终止日期)*/
    @Override
    public ResultData saveInsuranceOtherICInfo(SaveInsuranceOtherICInfo info, String userName, String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            // 批减、批退时，校验批单金额是否大于保费
            if (checkEndorsementMoneyOfOther(info, resultData,0)) return resultData;

            String endorsementId = info.endorsementNumber;
            // 校验批单号是否已经存在
            checkEndorsementId(resultData, endorsementId);
            if ("false".equals(resultData.getResult())) return resultData;

            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间
            Date now = new Date();
            SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String logTime = myFmt2.format(now);
            //1. 保存保险 人信息
            TInsuranceCarInfoModel carInfoModel = insuranceCarInfoRepository.findOne(info.carid);
            carInfoModel.setInsName(info.cusName);
            carInfoModel.setSex(info.sexuallity);
            carInfoModel.setClientype(info.cusType);
            carInfoModel.setPapersId(info.id);
            carInfoModel.setInsTel(info.cusTel);
            carInfoModel.setProvince(info.province);
            carInfoModel.setCity(info.city);
            carInfoModel.setDistrict(info.region);
            carInfoModel.setPostcode(info.postNumber);
            carInfoModel.setAddress(info.detailAddress);
            carInfoModel.setUpdateid(userName);
            carInfoModel.setUpdatetime(nowdate);
            insuranceCarInfoRepository.save(carInfoModel);
            //2.保存交强险信息
            TInsBuyModel insBuyModel = insBuyRepository.findByCarId(info.carid);
            if (insBuyModel == null) {
                insBuyModel = new TInsBuyModel();
                insBuyModel.setCarid(info.carid);
            }

            insBuyModel.setForcedOpTime(info.issuingDate);
            insBuyModel.setForcedYear(info.preiod);
            insBuyModel.setForcedInsCom(info.insuranceCpy);
            if (info.additionalPremium != null) {
                insBuyModel.setForcedCost(BigDecimal.valueOf(info.additionalPremium).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            insBuyModel.setForcedNumber(info.policyNumber);
            insBuyModel.setForcedInsureStart(info.invalidStart);
            insBuyModel.setForcedInsureEnd(info.invalidEnd);
            insBuyModel.setForcedEnd(info.policyTerminationDate);
            insBuyModel.setUpdateid(userName);
            insBuyModel.setUpdatetime(nowdate);
            insBuyModel = insBuyRepository.save(insBuyModel);//保存并返回

            //3.保存批单信息 (因之前的表设计的关系，这里批单号为空的时候，仍然需向批单表中插入一条批单信息为空的批单记录。故这里不判断批单号是否为空)
            TEndorsementInfoModel endorsementModel = new TEndorsementInfoModel();
            endorsementModel.setInsId(insBuyModel.getInsId());
            //  若为批退，设置批退时间
            if (info.endorsementType != null && info.endorsementType.equals("02")) {
                endorsementModel.setInsExitTime(logTime);
            }
            endorsementModel.setState("0");
            endorsementModel.setEndorsementId(info.endorsementNumber);
            endorsementModel.setEndorsementTime(info.endorsementDate);
            endorsementModel.setEndorsementType(info.endorsementType);
            endorsementModel.setInstype("0");
            endorsementModel.setRemark(info.endorsementNote);
            if (!StringUtils.isNullOrBlank(info.endorsementMoney)) {
                endorsementModel.setEndorsementMoney(new BigDecimal(info.endorsementMoney).setScale(2, BigDecimal.ROUND_UP)); //批单金额
            }
            // 计算批单手续费
            BigDecimal poundage = setPoundageOfOtherShop(info, permit, 0);
            // 设置手续费
            endorsementModel.setPoundage(poundage);

            endorsementModel.setUpdateid(userName);
            endorsementModel.setUpdatetime(nowdate);
            endorsementModel.setYear("1");
            info.pId = endorsementInfoRepository.save(endorsementModel).getPdId();
            //在购买详情表中存入交强险详细
            TInsBuyinfoModel buyinfoModel = new TInsBuyinfoModel();
            buyinfoModel.setPdId(info.pId);
            buyinfoModel.setInsname("交强险");
            if (info.additionalPremium != null) {
                buyinfoModel.setOriginalCost(BigDecimal.valueOf(info.additionalPremium).setScale(2, BigDecimal.ROUND_HALF_UP));
                buyinfoModel.setDiscountPrice(BigDecimal.valueOf(info.additionalPremium).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            buyinfoModel.setUpdateid(userName);
            buyinfoModel.setUpdatetime(nowdate);
            insBuyinfoRepository.save(buyinfoModel);

            List a = new ArrayList();
            Map b = new HashMap();
//            b.put("pId", info.pId);
            a.add(b);
            resultData.setPageData(new PageData(a, 0));
            resultData.setResult("true");
            resultData.setMessage("保存成功");

        } catch (Exception e) {
            resultData.setMessage("保存失败");
            logger.error("他店交强险保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public ResultData saveInsuranceOtherBCInfo(SaveInsuranceOtherInfo info, String userName, String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            // 批减、批退时，校验批单金额是否大于保费
            if (checkEndorsementMoneyOfOther(info, resultData, 1)) return resultData;

            String endorsementId = info.endorsementNumber;
            // 校验批单号是否已经存在
            checkEndorsementId(resultData, endorsementId);
            if ("false".equals(resultData.getResult())) return resultData;

            Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间
            Date now = new Date();
            SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String logTime = myFmt2.format(now);
            //1. 保存保险 人信息
            TInsuranceCarInfoModel carInfoModel = insuranceCarInfoRepository.findOne(info.carid);
            carInfoModel.setInsName(info.cusName);
            carInfoModel.setSex(info.sexuallity);
            carInfoModel.setClientype(info.cusType);
            carInfoModel.setPapersId(info.id);
            carInfoModel.setInsTel(info.cusTel);
            carInfoModel.setProvince(info.province);
            carInfoModel.setCity(info.city);
            carInfoModel.setDistrict(info.region);
            carInfoModel.setPostcode(info.postNumber);
            carInfoModel.setAddress(info.detailAddress);
            carInfoModel.setUpdateid(userName);
            carInfoModel.setUpdatetime(nowdate);
            insuranceCarInfoRepository.save(carInfoModel);
            //2.保存商业险保险信息
            TInsBuyModel insBuyModel = insBuyRepository.findByCarId(info.carid);
            if (insBuyModel == null) {
                insBuyModel = new TInsBuyModel();
                insBuyModel.setCarid(info.carid);
            }

            insBuyModel.setBusOpTime(info.issuingDate);
            insBuyModel.setBusYear(info.preiod);
            insBuyModel.setBusInsCom(info.insuranceCpy);
            if (info.additionalPremium != null) {
                insBuyModel.setBusCost(BigDecimal.valueOf(info.additionalPremium).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            insBuyModel.setBusNumber(info.policyNumber);
            insBuyModel.setBusInsureStart(info.invalidStart);
            insBuyModel.setBusInsureEnd(info.invalidEnd);
            insBuyModel.setBusEnd(info.policyTerminationDate);
            insBuyModel.setUpdateid(userName);
            insBuyModel.setUpdatetime(nowdate);
            insBuyModel = insBuyRepository.save(insBuyModel);//保存并返回

            //3.保存批单信息  且更改以前的使用状态 (因之前的表设计的关系，这里批单号为空的时候，仍然需向批单表中插入一条批单信息为空的批单记录。故这里不判断批单号是否为空)

            TEndorsementInfoModel endorsementModel = new TEndorsementInfoModel();
            //  若为批退，设置批退时间
            if (info.endorsementType != null && info.endorsementType.equals("02")) {
                endorsementModel.setInsExitTime(logTime);
            }
            endorsementModel.setState("0");
            endorsementModel.setInsId(insBuyModel.getInsId());
            endorsementModel.setInstype("1");
            endorsementModel.setEndorsementId(info.endorsementNumber);
            endorsementModel.setEndorsementTime(info.endorsementDate);
            endorsementModel.setEndorsementType(info.endorsementType);
            endorsementModel.setRemark(info.endorsementNote);
            if (!StringUtils.isNullOrBlank(info.endorsementMoney)) {
                endorsementModel.setEndorsementMoney(new BigDecimal(info.endorsementMoney).setScale(2, BigDecimal.ROUND_UP)); //批单金额
            }
            // 计算批单手续费
            BigDecimal poundage = setPoundageOfOtherShop(info, permit, 1);
            // 设置手续费
            endorsementModel.setPoundage(poundage);

            endorsementModel.setUpdateid(userName);
            endorsementModel.setUpdatetime(nowdate);
            endorsementModel.setYear(info.year);
            endorsementInfoRepository.save(endorsementModel);

            //在购买详情表中存入商业险详细
            info.pId = endorsementInfoRepository.save(endorsementModel).getPdId();
            if (info.info != null && info.info.size() != 0) {
                for (TInsBuyinfoModel model : info.info) {
                    model.setUpdateid(userName);
                    model.setUpdatetime(nowdate);
                    model.setPdId(info.pId);
                    insBuyinfoRepository.save(model);
                }
            }

            List a = new ArrayList();
            Map b = new HashMap();
//            b.put("pId", info.pId);
            a.add(b);
            resultData.setResult("true");
            resultData.setMessage("保存成功");

        } catch (Exception e) {
            resultData.setMessage("保存失败");
            logger.error("他店商业强险保存失败", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }

        return resultData;
    }

    @Override
    public ResultData getInsuranceHistoryInfo(String carid) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            resultData.setPageData(new PageData(insuranceRepository.getInsuranceHistoryInfo(carid), 0));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("他店保险历史记录", e);
        }
        return resultData;
    }

    @Override
    public ResultData getBuyInfo(Integer pId) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List<TInsBuyinfoModel> info = insBuyinfoRepository.findBypdId(pId);
            resultData.setPageData(new PageData(info, 0));
            resultData.setResult("true");
            resultData.setMessage("成功");
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("获取保险详情失败", e);
        }
        return resultData;
    }

    //计算他店手续费
    //state 客户类别   type 保险类别 交强险0  商业险1   additionalPremium 保险费用
    private Map<String, Object> countFactorage(String state, double additionalPremium, TInsBuyModel buyModel, String permit, String type) {
        Map<String, Object> result = new HashMap();

        double a = 0;
        result.put("result", false);
        //1.获取保险公司
        //2.获取费率
        //3.计算
        try {
            if (type.equals("0")) {
                Integer forc_com = 保险公司设置Repository.findByinsName(buyModel.getForcedInsCom());
                List result2 = insuranceRepository.getInsFactorage(forc_com.toString(), "0", permit, state);
                if (result2 != null) {
                    Map map1 = (Map) result2.get(0);
                    if (map1.get("交强险手续费") != null) {
                        Double jq = Double.parseDouble(map1.get("交强险手续费").toString());
                        a = jq * additionalPremium / 100;
                        result.put("result", true);
                        result.put("countFactorage", a);
                    }
                }
            } else {
                Integer bus_com = 保险公司设置Repository.findByinsName(buyModel.getBusInsCom());
                List result2 = insuranceRepository.getInsFactorage("", bus_com.toString(), permit, state);
                if (result2 != null) {
                    Map map1 = (Map) result2.get(0);
                    if (map1.get("商业险手续费") != null) {
                        Double sy = Double.parseDouble(map1.get("商业险手续费").toString());
                        a = sy * additionalPremium / 100;
                        result.put("result", true);
                        result.put("countFactorage", a);
                    }
                }
            }
        } catch (Exception e) {
            result.put("result", false);
        }
        return result;
    }

    @Override
    public ResultData saveInsuranceBcManyYears(List<TEndorsementInfoModel> modelList, String userName, String permit, Integer carId) {
        ResultData resultData = new ResultData("false", null, null);
        Timestamp nowdate = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());//获取当前时间
        TInsBuyModel insBuyModel = insBuyRepository.findByCarId(carId);//carId为必传数据
        try {
            if (StringUtils.isNullOrBlank(insBuyModel.getInsId())) {
                throw new AppException("保存失败!请确认填写用户车辆信息并保存！");
            }
            if (modelList == null || modelList.size() == 0) {
                throw new AppException("保存失败!请确认输入年份是否不等于0！");
            }

            //1.判断输入年份是否大于库中启用最大年    若大于 则跳转 2    若小于 则跳3
            Integer maxYear = endorsementInfoRepository.findMixYear(insBuyModel.getInsId(), "1", "0");
            //2.当有一保一年或两年  改为一保三年四年    有则改为启用   无责新增
            if (maxYear < modelList.size()) {
                for (TEndorsementInfoModel model : modelList) {
                    TEndorsementInfoModel endorsementInfoModel = null;
                    List<TEndorsementInfoModel> endorsementInfoModelList = endorsementInfoRepository.findbuyYearAndinsId(insBuyModel.getInsId(), model.getYear(), "1");
                    if (endorsementInfoModelList != null && endorsementInfoModelList.size() != 0) { //  存在 则 启用
                        endorsementInfoModel = endorsementInfoModelList.get(0);
                        endorsementInfoModel.setEndorsementType(null);
                        endorsementInfoModel.setRemark(null);
                        endorsementInfoModel.setState("0");
                        endorsementInfoModel.setUpdateid(userName);
                        endorsementInfoModel.setUpdatetime(nowdate);
                        endorsementInfoRepository.save(endorsementInfoModel);
                    } else {//不存在 则新增
                        endorsementInfoModel = model;
                        endorsementInfoModel.setInsId(insBuyModel.getInsId());
                        endorsementInfoModel.setInstype("1");
                        endorsementInfoModel.setState("0");
                        endorsementInfoModel.setUpdateid(userName);
                        endorsementInfoModel.setUpdatetime(nowdate);
                        endorsementInfoRepository.save(endorsementInfoModel);
                    }
                }
            }
            //3.当由一保5年  改为 一保 一年两年 ，则把年限大于两年的改为 停用
            else if (maxYear > modelList.size()) {
                Integer a = modelList.size();
                endorsementInfoRepository.updateStateByMaxY("1", insBuyModel.getInsId(), "1", "0", a.toString());
            }
            resultData.setResult("true");
            resultData.setMessage("保存一保多年成功");
        } catch (AppException e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            resultData.setMessage(e.getMessage());
            resultData.setResult("false");
        } catch (Exception e) {
            resultData.setMessage("保存一保多年失败");
            logger.error("保存一保多年信息失败", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }

        return resultData;
    }

    @Override
    public void exportInsuranceAccountInfo(HttpServletResponse response, String liveName, String permit, GetInsuranceInfoListRequest request) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/LSH_经销商_保险业务台账导出模板.xlsx")
                    .setFileName("经销商_保险业务台账导出模板.xlsx")
                    .setSource(ExportInsuranceAccountInfoSource)
                    .setStartCellIndex(0)
                    .setEndCellIndex(65)
                    .setStaticSheet(false)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("tciNo", request.tciNo)
                    .addParam("vciNo", request.vciNo)
                    .addParam("tciCompany", request.tciCompany)
                    .addParam("vciCompany", request.vciCompany)
                    .addParam("salesName", request.salesName)
                    .addParam("status", request.status)
                    .addParam("username", request.username)
                    .addParam("userPhone", request.userPhone)
                    .addParam("vin", request.vin)
                    .addParam("type", request.type)
                    .addParam("startEnterDate", request.startEnterDate)
                    .addParam("endEnterDate", request.endEnterDate)
                    .addParam("startDueDate", request.startDueDate)
                    .addParam("endDueDate", request.endDueDate)
                    .addParam("startOrderDate", request.startOrderDate)
                    .addParam("endOrderDate", request.endOrderDate)
                    .addParam("startExpectInvoiceDate", request.startExpectInvoiceDate)
                    .addParam("endExpectInvoiceDate", request.endExpectInvoiceDate)
                    .addParam("orderRelyType", request.orderRelyType)
                    .addParam("pageSize", request.getPageSize())
                    .addParam("pageIndex", request.getPageIndex())
                    .addParam("forceInsuranceStartDate",request.forceInsuranceStartDate)
                    .addParam("forceInsuranceEndDate",request.forceInsuranceEndDate)
                    .addParam("commercialInsuranceStartDate",request.commercialInsuranceStartDate)
                    .addParam("forceInsuranceEndDate",request.commercialInsuranceEndDate);

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出本店保险台账程序异常", e);
        }
    }

    @Override
    @Transactional
    public ResultData deleteSuggestPlan(String permit, Integer carId) {
        // 判断当前保险方案是否已经被使用 （需求未定）
        // TODO: 2017/6/13
        //保险已被使用,返回”此推荐方案已被使用，无法删除“
//        return new ResultData("true","此推荐方案已被使用，无法删除",null);

        //保险未被使用，1：读取要删除的数据 2：把数据放入回收表 3：删除数据
        //读取要删除的数据
        List<Lsh保险设置Model> datas = lsh保险设置Repository.findByPermitAndCarId(permit, carId);
        //把数据放入回收表
        if (datas != null && !datas.isEmpty()) {
            TDataRecycleModel model = new TDataRecycleModel();
            model.setPid(null);
            model.setObjectType("lsh保险设置");
            model.setObjectName("permit:" + permit + "," + "carId" + carId);
            model.setObjectContent(JSON.toJSONString(datas));
            model.setCreateTime(new Timestamp(new Date().getTime()));
            dataRecycleRepository.save(model);
            //删除数据
            lsh保险设置Repository.delBy许可And车型编号(permit, carId);
            return new ResultData("true", "删除成功", null);
        } else {
            return new ResultData("false", "数据不存在，删除失败！", null);
        }
    }

    // 设置本店批单手续费 (type:0交强险，1商业险)
    private BigDecimal setPoundageOfThisShop(getUpdateInsuranceOrderInfo realInsFail, int type) {
        BigDecimal poundage = null;
        //客户类型  （1-非营业性个人, 2-公司）
        String userTypeNum = "2";  // 默认设置为公司
        if ("非营业性个人".equals(realInsFail.UserType)) {
            userTypeNum = "1";
        }
        //保险公司编号
        Integer insuranceCompanyNum = lsh保险公司设置Repository.findByinsName(realInsFail.InsuranceOutCompany);
        //许可
        String permit = realInsFail.permit;
        Lsh保险手续费ModelPK key = new Lsh保险手续费ModelPK();
        key.set保险公司编号(insuranceCompanyNum);
        key.set客户类别(userTypeNum);
        key.set许可(permit);
        Lsh保险手续费Model insuranceFee = lsh保险手续费Repository.findOne(key);
        double rate;
        if (0 == type) {  // 交强险
            if (StringUtils.isNullOrBlank(insuranceFee.get交强险手续费())) {
                rate = 0;  // 费率设置为0
                // 记录日志
                logger.warn("本店保险-交强险-批单：交强险手续费没有设置!许可={}，保险公司编号={}，客户类型={}", permit, insuranceCompanyNum, userTypeNum);
            } else {
                rate = Double.parseDouble(insuranceFee.get交强险手续费()) * 0.01;
            }
        } else {  // 商业险
            if (StringUtils.isNullOrBlank(insuranceFee.get商业险手续费())) {
                rate = 0;  // 费率设置为0
                // 记录日志
                logger.warn("本店保险-商业险-批单：商业险手续费没有设置!许可={}，保险公司编号={}，客户类型={}", permit, insuranceCompanyNum, userTypeNum);
            } else {
                rate = Double.parseDouble(insuranceFee.get商业险手续费()) * 0.01;
            }
        }

        // 设置手续费
        if (!StringUtils.isNullOrBlank(realInsFail.endorsementMoney)) {
            poundage = new BigDecimal(new DecimalFormat("#.00").format(realInsFail.endorsementMoney * rate));
        }
        return poundage;
    }

    // 计算他店保险批单手续费 （type : 0本店 ，1他店）
    private BigDecimal setPoundageOfOtherShop(SaveInsuranceOtherICInfo info, String permit, int type) {
        BigDecimal poundage = null;
        //保险公司编号
        Integer insuranceCompanyNum = lsh保险公司设置Repository.findByinsName(info.insuranceCpy);
        Lsh保险手续费ModelPK key = new Lsh保险手续费ModelPK();
        key.set保险公司编号(insuranceCompanyNum);
        key.set客户类别(info.cusType);
        key.set许可(permit);
        Lsh保险手续费Model insuranceFee = lsh保险手续费Repository.findOne(key);
        double rate;
        if (0 == type) {  // 交强险
            if (StringUtils.isNullOrBlank(insuranceFee.get交强险手续费())) {
                rate = 0;  // 费率设置为0
                // 记录日志
                logger.warn("他店保险-交强险-批单：交强险手续费没有设置!许可={}，保险公司编号={}，客户类型={}", permit, insuranceCompanyNum, info.cusType);
            } else {
                rate = Double.parseDouble(insuranceFee.get交强险手续费()) * 0.01;
            }
        } else {  // 商业险
            if (StringUtils.isNullOrBlank(insuranceFee.get商业险手续费())) {
                rate = 0;  // 费率设置为0
                // 记录日志
                logger.warn("他店保险-商业险-批单：商业险手续费没有设置!许可={}，保险公司编号={}，客户类型={}", permit, insuranceCompanyNum, info.cusType);
            } else {
                rate = Double.parseDouble(insuranceFee.get商业险手续费()) * 0.01;
            }
        }
        if (!StringUtils.isNullOrBlank(info.endorsementMoney)) {
            poundage = new BigDecimal(new DecimalFormat("#.00").format(info.endorsementMoney * rate));
        }
        return poundage;
    }

    // 校验批单号是否存在
    private void checkEndorsementId(ResultData resultData, String endorsementId) {
        resultData.setResult("true");
        if (!StringUtils.isNullOrBlank(endorsementId)) {
            List<TEndorsementInfoModel> models = endorsementInfoRepository.findByEndorsementId(endorsementId);
            List<Lsh保险申请表附属详细Model> model1s = 保险申请表附属详细repository.findBy批单号(endorsementId);
            if ((models != null && !models.isEmpty()) || (model1s != null && !model1s.isEmpty())) {
                logger.error("批单号不可以重复");
                resultData.setMessage("批单号不可以重复");
                resultData.setResult("false");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
    }

    // 本店-校验批单金额是否大于保费
    private boolean checkEndorsement(getUpdateInsuranceOrderInfo realInsFail, ResultData resultData) {
        if ("01".equals(realInsFail.insuranceOrderRelyType) || "02".equals(realInsFail.insuranceOrderRelyType)) {
            Double premium = realInsFail.InsuranceMoney.doubleValue(); // 保费
            Double endorsementMoney = Math.abs(realInsFail.endorsementMoney);  // 批单金额的绝对值
            if (endorsementMoney > premium) {
                resultData.setMessage("批减、批退金额不可以超过保费");
                return true;
            }
        }
        return false;
    }

    // 他店-校验批单金额是否大于保费  (type:0他店交强险 1他店商业险)
    private boolean checkEndorsementMoneyOfOther(SaveInsuranceOtherICInfo info, ResultData resultData, int type) {
        if ("01".equals(info.endorsementType) || "02".equals(info.endorsementType)) {
            Double premiun = null;
            if (0 == type) {
                premiun = info.additionalPremium;
            } else {
                premiun = info.currentYearPremium;
            }
            if (Math.abs(info.endorsementMoney) > premiun) {
                resultData.setMessage("批减、批退金额不可以超过保费");
                return true;
            }
        }
        return false;
    }

    @Override
    public List getInsDefeatedResonRpt() {
        return insuranceRepository.getInsDefeatedResonRpt();
    }

    @Override
    public List getInsuranceCompany(){
        return insuranceRepository.getInsuranceCompany();
    }
    /**
     * （1）计算“报价保险详细表”险种手续费。
     * （2）计算“报价保险表”的商业手续费 （返回值）
     * @param result
     * @param permit
     * @param state
     * @param InsuranceId
     * @return
     */
    private BigDecimal setCharge(List result, String permit, String state, String InsuranceId) {
        DecimalFormat df = new DecimalFormat("#0.00");
        //  one 用来计算（一年N保）商业手续费
        BigDecimal one = new BigDecimal(0);
        if (result != null) {
            Map map = (Map) result.get(0);
            Lsh保险手续费Model mode = lsh保险手续费Repository.finCharge(Integer.parseInt(map.get("商业险公司编号").toString()), permit, state);
            Lsh保险手续费Model mode2 = lsh保险手续费Repository.finCharge(Integer.parseInt(map.get("交强险公司编号").toString()), permit, state);
//           List<报价保险详细表Model> listModel2 =报价保险详细表Repository.findInsurId(Integer.parseInt(InsuranceId));
            List<Map> listModel = insuranceRepository.getInsuianceChange(InsuranceId);

            if (mode != null && listModel != null && listModel.size() > 0) {
                Map per = DaoFromMap.getMap(mode);
                Map per2 = DaoFromMap.getMap(mode2);

                for (int i = 0; i < listModel.size(); i++) {

                    // 保险手续费表 和 报价保险详细表的险种 名字不匹配，所以要调和处理
                    if ("车上人员责任险 - 乘客".equals(listModel.get(i).get("险种"))) {
                        listModel.get(i).put("车上人员责任险 - 乘客", "车上人员责任险乘客");
                    } else if ("车上人员责任险 - 司机".equals(listModel.get(i).get("险种"))) {
                        listModel.get(i).put("车上人员责任险 - 司机", "车上人员责任险司机");
                    } else if ("倒车镜、车灯单独损失险".equals(listModel.get(i).get("险种"))) {
                        listModel.get(i).put("倒车镜、车灯单独损失险", "倒车镜车灯单独损失险");
                    }
					
					Double rate = 0d;
                    BigDecimal charge = new BigDecimal(0);

                    //计算手续费
                    if (per != null){
                        //（1）如果险种对应手续费没有则取商业手续费 （2） 交强险对应交强险，交强险除外 （3）其它的则都属于商业险   车船税除外
                        if (per.containsKey(listModel.get(i).get("险种") + "手续费")
                                && per.get(listModel.get(i).get("险种") + "手续费") != null
                                && !Strings.isNullOrEmpty(per.get(listModel.get(i).get("险种") + "手续费").toString())
                                && !"车船税".equals(listModel.get(i).get("险种"))
                                ) {

                            //获取手续费率
                            if ("交强险".equals(listModel.get(i).get("险种"))) {
                                rate = Double.parseDouble(per2.get(listModel.get(i).get("险种") + "手续费").toString()) / 100;
                            } else {
                                rate = Double.parseDouble(per.get(listModel.get(i).get("险种") + "手续费").toString()) / 100;
                            }


                            //获取不计免赔
                            BigDecimal buji =null;
                            if (StringUtils.isNullOrBlank(listModel.get(i).get("不计免赔"))) {
                                buji = new BigDecimal("0");
                            } else {
                                 buji = NumberUtils.getBigDecimalValue(listModel.get(i).get("不计免赔").toString());
                            }
                            if(listModel.get(i).get("折后价")!= null
                                    && !Strings.isNullOrEmpty(listModel.get(i).get("折后价").toString())){
                                //设置手续费 算法：（折后价+不计免赔） * 手续费率
                                charge = ((NumberUtils.getBigDecimalValue(listModel.get(i).get("折后价").toString())).add(buji))
                                        .multiply(new BigDecimal(rate));
                            }else {
                                charge = (buji.multiply(new BigDecimal(rate)));

                            }

                        } else {
                            //交强险除外
                            if (!"交强险".equals(listModel.get(i).get("险种"))
                                    && per.get("商业险手续费") != null
                                    && !Strings.isNullOrEmpty(per.get("商业险手续费").toString())) {
                                //获取不计免赔
                                BigDecimal buji =null;
                                if (StringUtils.isNullOrBlank(listModel.get(i).get("不计免赔"))) {
                                    buji = new BigDecimal("0");
                                } else {
                                    buji = NumberUtils.getBigDecimalValue(listModel.get(i).get("不计免赔").toString());
                                }
                                //获取手续费率
                                rate = Double.parseDouble(per.get("商业险手续费").toString()) / 100;
                                if(listModel.get(i).get("折后价")!= null
                                        && !Strings.isNullOrEmpty(listModel.get(i).get("折后价").toString())){


                                    //设置手续费 算法：（折后价+不计免赔） * 手续费率
                                    charge = ((NumberUtils.getBigDecimalValue(listModel.get(i).get("折后价").toString())).add(buji))
                                            .multiply(new BigDecimal(rate));
                                }else {
                                    charge = (buji.multiply(new BigDecimal(rate)));

                                }
                            }
                        }
                        if (charge != null
                                && listModel.get(i).get("险种") != null && !Strings.isNullOrEmpty(listModel.get(i).get("险种").toString())
                                && listModel.get(i).get("保险编号") != null && !Strings.isNullOrEmpty(listModel.get(i).get("保险编号").toString())
                                && listModel.get(i).get("第N年") != null && !Strings.isNullOrEmpty(listModel.get(i).get("第N年").toString())) {
                            报价保险详细表Repository.updateChange(df.format(charge.setScale(2, BigDecimal.ROUND_HALF_UP)), listModel.get(i).get("险种").toString(),
                                    Integer.parseInt(listModel.get(i).get("保险编号").toString()), Integer.parseInt(listModel.get(i).get("第N年").toString()));
                        }

                        //此处计算的是“报价保险表”的所有商业险的手续费，交强险不属于商业险   车船税不属于保险
                        if (!"交强险".equals(listModel.get(i).get("险种")) && charge != null && !"车船税".equals(listModel.get(i).get("险种"))) {
                            one = one.add(charge.setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    }
                }
            }
        }
        return one;
   }

    private void updateCommerFirstYearTotalPrice(String insCode) {
        报价保险表Model insuranceModel = 报价保险表Repository.findOne(Integer.valueOf(insCode));
        // 得到计算的首年商业险总价
        List<Map> resultList = insuranceRepository.getInsCost(insCode);
        // 设置商业险类型为详细模式 (总价模式是1 详细模式是0)
        insuranceModel.setIsCommerTotal("0");
        // 更新首年商业险总价的值
        if (resultList != null && !resultList.isEmpty() && resultList.get(0).get("首年商业险") != null) {
            insuranceModel.setCommerFirstYearTotalPrice(new BigDecimal(resultList.get(0).get("首年商业险").toString()));
        }

    }
}

